Creating clone of an object not working with virtual base class

断了今生、忘了曾经 提交于 2019-12-06 16:09:28

问题


#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.



来源:https://stackoverflow.com/questions/3831370/creating-clone-of-an-object-not-working-with-virtual-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!