title: Copying derived entities using only base class pointers, (without exhaustive testing!) - C++
body: <p>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?</p>
  
  <p>Looking around it would seem possible (if incredibly tedious) to use the <code>dynamic_cast</code> 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.</p>
  
  <p>Another more elegant solution I have come across is as follows:</p>
  
  <pre><code>class Base
  {
  public:
     Base(const Base&amp; other);
     virtual Base* getCopy();
     ...
  }
  
  class Derived :public Base
  {
     Derived(const Derived&amp; other);
     virtual Base* getCopy();
     ...
  }
  
  Base* Base::getCopy()
  {
     return new Base(*this));
  }
  
  Base* Derived::getCopy()
  {
     return static_cast&lt;Base*&gt;(new Derived(*this));
  }
  </code></pre>
  
  <p>Then by calling <code>getCopy()</code> 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 <code>getCopy()</code> function to be in all derived classes, and does away with the need to test against all possible derived objects.</p>
  
  <p>Essentially, is this wise? or is there a better, even neater way of doing this?</p>