Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a Polymorphic object in C++

Tags:

c++

clone

I have base-class Base from which is derived Derived1, Derived2 and Derived3.

I have constructed an instance for one of the the derived classes which I store as Base* a. I now need to make a deep copy of the object which I will store as Base* b.

As far as I know, the normal way of copying a class is to use copy constructors and to overload operator=. However since I don't know whether a is of type Derived1, Derived2 or Derived3, I cannot think of a way of using either the copy constructor or operator=. The only way I can think of to cleanly make this work is to implement something like:

class Base { public:   virtual Base* Clone() = 0;  }; 

and the implement Clone in in the derived class as in:

class Derivedn : public Base { public:   Base* Clone()    {     Derived1* ret = new Derived1;     copy all the data members   } }; 

Java tends to use Clone quite a bit is there more of a C++ way of doing this?

like image 242
doron Avatar asked Feb 28 '11 23:02

doron


People also ask

How do you copy an object Polymorphically?

(There is a protected, not public, "clone" method inherited from Object.) The way to clone polymorphically is to obtain a copy from the superclass's clone() method, and then perform custom copying operations specific to this class.

What is the difference between clone and copy?

clone - create something new based on something that exists. copying - copy from something that exists to something else (that also already exists).

What is clone in CPP?

In C++ copying the object means cloning. There is no any special cloning in the language. As the standard suggests, after copying you should have 2 identical copies of the same object.


1 Answers

This is still how we do stuff in C++ for polymorphic classes, but you don't need to do the explicit copy of members if you create a copy constructor (possibly implicit or private) for your objects.

class Base { public:   virtual Base* Clone() = 0; };  class Derivedn : public Base { public:   //This is OK, its called covariant return type.   Derivedn* Clone()    {     return new Derivedn(*this);   } private:   Derivedn(const Derivedn&) : ... {} }; 
like image 190
Michael Anderson Avatar answered Oct 05 '22 23:10

Michael Anderson