lowq
lowq

Reputation: 628

Performing a deep copy on derived classes

This has been bugging me lately. Say I have a base class Base. If I have multiple derived classes on top of Base, such as DerivedA and DerivedB, a deep copy gets to be a pain.

OtherClass(const OtherClass & _rhs)
{
    //I have a list of Base *, now I must assign a class id to each derived class to properly create a new one.
    //...
}

Is there any way to get around this?

Upvotes: 1

Views: 1402

Answers (1)

tibur
tibur

Reputation: 11636

You should define a clone method in your Base class:

virtual Base * clone() const = 0;

Each derived class implement that clone method:

virtual DerivedA * clone() const {
    return new DerivedA(*this);
}

Then your OtherClass just has to iterate and call clone method over each instance of Base* in your list.

Upvotes: 9

Related Questions