Suppose we have the following class hierarchy:
class Base { ... }; class Derived1 : public Base { ... }; class Derived2 : public Base { ... };
Given a Base* which could point to either a Derived1 or Derived2 object how can I make a copy of the actual object given that it’s concrete type is unknown. I thought of defining copy constructors but I don’t think this is possible without knowing the actual types involved. The only solution I can think of is defining a clone() method on each type in the hierarchy. Can anybody think of something more elegant?
Unfortunately a virtual clone/copy pattern is your only real choice.
There are variations of this, but essentially they all come down to writing functions for each type that can return a new copy.