title: Cloning a derived type more elegantly
body: <p>I have a pure virtual base class and several derived classes, and I need to clone the derived's.  I did this initially:</p>
  
  <pre><code>struct base {
     virtual base* clone() = 0;
  }
  
  struct derived: public base {
     base* clone() {
        derived* d = new derived;
        /*copy members, etc.*/
        return d;
     }
  }
  </code></pre>
  
  <p>This works fine, except that the clone function implementations in all my derived classes are IDENTICAL except for the returned type (which will be one of the derived types).  In other words, all the operations that I do during the cloning process are common to the base class.  So, the next thing I did was add a template function to my base class:</p>
  
  <pre><code>struct base {
     virtual base* clone() = 0;
  
     template &lt;typename T&gt;
     T* make_clone() {
        T* d = new T;
        /*copy members, etc.*/
        return d;
     }
  }
  
  struct derived: public base {
     base* clone() {return base::make_clone&lt;derived&gt;();}
  }
  </code></pre>
  
  <p>This works too, but it seems a bit inelegant and I feel like there should be a cleaner approach with fewer function calls and elimination of the one-line functions in all my derived classes.  Is there some language feature or design pattern that I can play with to clean this up a bit?  Also just to clarify, the caller does not know the derived type of the <code>base*</code> that it needs to clone.  Otherwise I could just call <code>base::make_clone&lt;derived&gt;</code> directly.</p>