1

I want to copy objects in c++. The problem is that i have derived classes with polymorphism, as shown i the pseudocode below:

class BaseCl { some virtual functions };
class DerivedClass : public BaseCl { ... };

...

BaseCl * b1 = new DerivedClass();
BaseCl * b2 = new "copy of b1"; (just pseudocode)

The problem is the last line:

I want to copy an object of the class "BaseCl", but because of the polymorphism the copy must be just like the original object of "DerivedClass".

What is the best way to do that?

Thank you very much, any help is appreciated.

Edit: Problem has been solved:

Inserted:

virtual BaseCl *clone() = 0;

in the base class and

DerivedCl *clone() {return new DerivedCl(*this);}

in the derived class. Thank you all.

MarkusX
  • 11
  • 2
  • This is more or less the same issue described here: http://stackoverflow.com/questions/12447427/c-maintaining-a-mixed-collection-of-subclass-objects/12447459#12447459 – Zdeslav Vojkovic Sep 25 '12 at 07:38

2 Answers2

6

You need to define a function in BaseC1 that makes a clone. Something like:

class BaseCl
{
    virtual BaseCl* clone() {return new BaseC1(*this);}
};
class DerivedClass : public BaseCl
{
    virtual BaseCl* clone() {return new DerivedClass(*this);}
};
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
  • You forgot to type the return of the function. I edited your answer. – Basile Starynkevitch Sep 25 '12 at 07:33
  • Hmm, i get another problem, when i try this: virtual BaseCl* clone() {return new BaseCl(*this);} BaseCl.h:45: error: cannot allocate an object of abstract type ‘BaseCl’ ../BaseCl.h:21: note: because the following virtual functions are pure within ‘BaseCl’: ... So are virtual Functions the problem? – MarkusX Sep 25 '12 at 07:53
  • You can actually have a different return type in the derived class, so that if you have a pointer to the derived class, you don't have to cast the result of `Clone`. – Mark Ingram Sep 25 '12 at 09:06
0

The key of runtime polymorphism is that operations must be implemented in the most derived object, since it is the one than know everything it has to be known to perform them. All bases must expose virtual functions to be called by base pointers.

You can devine at the base level a virtual BaseCl* clone() function, and override it your derived classes to return new DerivedClass(*this)

Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63