title: Copying a Polymorphic object in C++
body: <p>I have base-class <code>Base</code> from which is derived <code>Derived1</code>, <code>Derived2</code> and <code>Derived3</code>.</p>
  
  <p>I have constructed an instance for one of the the derived classes which I store as <code>Base* a</code>. I now need to make a deep copy of the object which I will store as <code>Base* b</code>. </p>
  
  <p>As far as I know, the normal way of copying a class is to use copy constructors and to overload <code>operator=</code>. However since I don't know whether <code>a</code> is of type <code>Derived1</code>, <code>Derived2</code> or <code>Derived3</code>, I cannot think of a way of using either the copy constructor or <code>operator=</code>. The only way I can think of to cleanly make this work is to implement something like:</p>
  
  <pre><code>class Base
  {
  public:
    virtual Base* Clone() = 0;
  
  };
  </code></pre>
  
  <p>and the implement <code>Clone</code> in in the derived class as in:</p>
  
  <pre><code>class Derivedn : public Base
  {
  public:
    Base* Clone() 
    {
      Derived1* ret = new Derived1;
      copy all the data members
    }
  };
  </code></pre>
  
  <p>Java tends to use <code>Clone</code> quite a bit is there more of a C++ way of doing this?</p>