title: How to clone subclasses without duplicating code?
body: <p>Class Plus inherits from class Expression. </p>
  
  <pre><code>class Expression
  {
   public:
    virtual Expression* clone() const = 0;
  };
  class Plus : public Expression
  {
   public:
   Plus( Expression* lhs, Expression* rhs ) :Expression( lhs, rhs) {};
   Plus* clone() const;
  };
  </code></pre>
  
  <p>I'm implementing a <code>copy</code> function. The current implementation will leak memory if one of the <code>clone</code>s or the <code>Plus</code> fails.</p>
  
  <pre><code>Plus* Plus::clone() const  {
          return new Plus(tree_left-&gt;clone(), tree_right-&gt;clone());
  }
  </code></pre>
  
  <p>and I think something like this would solve the problem:</p>
  
  <pre><code>Plus* Plus::clone() const  {
          Expression *tree_left_clone = nullptr;
          Expression *tree_right_clone = nullptr;
          Expression *plus_clone = nullptr;
          try {
               tree_left_clone = tree_left-&gt;clone();
               tree_right_clone = tree_right-&gt;clone()
               plus_clone = new Plus( tree_left_clone, tree_right_clone );
          } catch (const bad_alloc&amp; e ) {
               delete tree_left_clone;
               delete tree_right_clone;
               delete plus_clone;
          }
          return plus_clone;
  }
  </code></pre>
  
  <p>But there's a lot of similar operators including Minus, Times, Divided, Power etc. And I'd have to duplicate <code>clone</code> for all of them. Is there a way to put this code in <code>Expression</code>?
  The problem I'm having is with the line in <code>clone</code> containing <code>new Plus</code>.</p>