Given a base class that is inherited by plethora of derived classes, and a program structure that requires you manage these via base class pointers to each entity. Is there a simple way to copy the entire derived object when only the base class pointer is known?
Looking around it would seem possible (if incredibly tedious) to use the dynamic_cast
call to check if a base pointer can be cast as the appropriate derived class, then copy it using the derived class's copy constructor. However this is not really an optimal solution partly due to the excessive use of dynamic_cast and also it would see a total headache to maintain and extend.
Another more elegant solution I have come across is as follows:
class Base
{
public:
Base(const Base& other);
virtual Base* getCopy();
...
}
class Derived :public Base
{
Derived(const Derived& other);
virtual Base* getCopy();
...
}
Base* Base::getCopy()
{
return new Base(*this));
}
Base* Derived::getCopy()
{
return static_cast<Base*>(new Derived(*this));
}
Then by calling getCopy()
on the Base class pointer to any derived object one still gets a base class pointer back but also the whole of the derived object has been copied. This method feels a lot more maintainable as it just requires a similar getCopy()
function to be in all derived classes, and does away with the need to test against all possible derived objects.
Essentially, is this wise? or is there a better, even neater way of doing this?