Creating clone of an object not working with virtu

2019-04-17 00:16发布

问题:

#include<iostream>
using namespace std;

class Something
{
  public:
  int j;
  Something():j(20) {cout<<"Something initialized. j="<<j<<endl;}
};

class Base
{
  private:
    Base(const Base&) {}
  public:
    Base() {}
    virtual Base *clone() { return new Base(*this); }
    virtual void ID() { cout<<"BASE"<<endl; }
};

class Derived : public Base
{
  private:
    int id;
    Something *s;
    Derived(const Derived&) {}
  public:
    Derived():id(10) {cout<<"Called constructor and allocated id"<<endl;s=new Something();}
    ~Derived() {delete s;}
    virtual Base *clone() { return new Derived(*this); }
    virtual void ID() { cout<<"DERIVED id="<<id<<endl; }
    void assignID(int i) {id=i;}
};


int main()
{
        Base* b=new Derived();
        b->ID();
        Base* c=b->clone();
        c->ID();
}//main

On running:

Called constructor and allocated id
Something initialized. j=20
DERIVED id=10
DERIVED id=0

My question is related to this, this and this post.

In the first link, Space_C0wb0y says

"Since the clone-method is a method of the actual class of the object, it can also create a deep-copy. It can access all members of the class it belongs to, so no problems there."

I don't understand how a deep copy can happen. In the program above, not even a shallow copy is happening. I need it to work even if the Base class is an abstract class. How can I do a deep copy here? Help please?

回答1:

Well, your copy constructor does nothing, so your clone method does nothing in the way of copying.

See line Derived(const Derived&) {}

EDIT: if you add code to copy by assignment all members of Derived, it will become a shallow copy. If you also copy (by making a new instance) your instance of Something, it will become a deep copy.