title: copying c++ abstract classes
body: <p>Ok heres some code.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;deque&gt;
  using namespace std;
  class A
  {
  public:
      virtual void Execute()
      {
          cout &lt;&lt; "Hello from class A" &lt;&lt; endl;
      }
  };
  class B: public A
  {
  public:
      void Execute()
      {
          cout &lt;&lt; "Hello from class B" &lt;&lt; endl;
      }
  };
  void Main()
  {
      deque&lt;A *&gt; aclasses = deque&lt;A*&gt;(0);
      deque&lt;A *&gt; aclasses2 = deque&lt;A*&gt;(0);
      A a1 = A();
      B b1 = B();
      aclasses.push_back(&amp;a1);
      aclasses.push_back(&amp;b1);
      aclasses[0]-&gt;Execute();
      aclasses[1]-&gt;Execute();
  
      //Now say I want to copy a class from aclasses to aclasses2
      //while perserving it's identity and making it a seperate entity, without
      //knowing the exact type it is.
  
      aclasses2.push_back(new A(*aclasses[0]));
      aclasses2.push_back(new A(*aclasses[1]));
      //Now my problem show itself
      for each(A * a in aclasses2)
          a-&gt;Execute();
      //Execute is called from the original class A both times.
  
  }
  </code></pre>
  
  <p>Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.</p>
  
  <p>Now the current modified version</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;deque&gt;
  using namespace std;
  class A
  {
  public:
      virtual void Execute()
      {
          cout &lt;&lt; "Hello from class A" &lt;&lt; endl;
      }
      virtual ~A() {}             // don't forget the virtual destructor
      virtual A* clone() const {
         return new A(*this);
      }
  };
  class B: public A
  {
  public:
      void Execute()
      {
          cout &lt;&lt; "Hello from class B" &lt;&lt; endl;
      }
      virtual B* clone() {     // return type is co-variant
         return new B( *this );
      }
  };
  void MainRUNNER()
  {
      deque&lt;A *&gt; aclasses = deque&lt;A*&gt;(0);
      deque&lt;A *&gt; aclasses2 = deque&lt;A*&gt;(0);
      A a1 = A();
      B b1 = B();
      aclasses.push_back(&amp;a1);
      aclasses.push_back(&amp;b1);
      aclasses[0]-&gt;Execute();
      aclasses[1]-&gt;Execute();
  
      //Now say I want to copy a class from aclasses to aclasses2
      //while perserving it's identity and making it a seperate entity, without
      //knowing the exact type it is.
  
      aclasses2.push_back(aclasses[0]-&gt;clone());
      aclasses2.push_back(aclasses[1]-&gt;clone());
      //Now my problem show itself
      for each(A * a in aclasses2)
          a-&gt;Execute();
      //Execute is called from the original class A both times.
  }
  </code></pre>