Object pointer vector, you need a deep copy of the vector, but objects are the base of inherited objects

I want to have a deep copy of a vector with pointers to objects, but the object can be either C or B. I know I'm confused (as I explain it), let me illustrate.

class A { A(const A& copyme) { } void UnableToInstantiateMeBecauseOf() =0; }; class B { B(const B& copyme) : A(copyme) {} }; class C { C(const C& copyme) : A(copyme) {} }; std::vector<A*>* CreateDeepCopy(std::vector<A*>& list) { std::vector<A*>* outList = new std::vector<A*>(); for (std::vector<A*>::iterator it = list.begin(); it != list.end(); ++it) { A* current = *it; // I want an copy of A, but it really is either an B or an C A* copy = magic with current; outList->push_back(copy); } return outList; } 

How to create a copy of an object that you donโ€™t have what inherited the type?

+4
source share
4 answers

Use cloning:

Copy object - save polymorphism

 class Super { public: Super();// regular ctor Super(const Super& _rhs); // copy constructor virtual Super* clone() const = 0; // derived classes to implement. }; // eo class Super class Special : public Super { public: Special() : Super() {}; Special(const Special& _rhs) : Super(_rhs){}; virtual Special* clone() const {return(new Special(*this));}; }; // eo class Special 

EDIT:

In your question, I noticed that your base class is abstract. This is great, this model is still working, I fixed it.

+4
source

Add the Clone () virtual method to your classes.

 A* copy = it->Clone(); class A { virtual A* Clone() { return new A(*this); } }; 

Override cloning in derived classes. The implementation is the same as in class A.

+2
source

In class A you can implement the pure virtual cloning function.

+2
source

As others have said, you need some kind of cloning mechanism. You might want to check out cloning_ptr Kevlin Henny in your excellent Clone Alone article.

+2
source

All Articles