I want to have a deep copy of an vector with pointers to objects, but the object can either be C or B. I know confusing (the way 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 an copy of an object of which you don't what inherited type it is?
Use cloning:
Copy object - keep 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:
I noticed in your question your base-class is abstract. That's fine, this model still works, I have amended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With