title: c++ assignment operator= overloading with derived classes
body: <p>I'm currently writing a complicated class and in it I basically need to copy a list of derived classes. The simplified version is, as follows:
  I have a base class from which I derive several other classes:</p>
  
  <pre><code>class Base
  {
  public:
      virtual void test(void)
      {
          cout &lt;&lt; "Base" &lt;&lt; endl;
      }
      Base(vector&lt;Base*&gt; *pointer)
      {
          pointer-&gt;push_back(this);
      }
      virtual Base&amp; operator=(const Base&amp; rhs)
      {
          cout &lt;&lt; "Base=" &lt;&lt; endl;
          return *this;
      }
  };
  class A : public Base
  {
  public:
      void test(void)
      {
          cout &lt;&lt; "A" &lt;&lt; endl;
      }
      A(vector&lt;Base*&gt; *pointer) : Base(pointer) {}
      A&amp; operator=(const A&amp; rhs)
      {
          cout &lt;&lt; "A=" &lt;&lt; endl;
          return *this;
      }
  };
  class B : public Base
  {
  public:
      void test(void)
      {
          cout &lt;&lt; "B" &lt;&lt; endl;
      }
      B(vector&lt;Base*&gt; *pointer) : Base(pointer) {}
      B&amp; operator=(const B&amp; rhs)
      {
          cout &lt;&lt; "B=" &lt;&lt; endl;
          return *this;
      }
  };
  </code></pre>
  
  <p>Then I create a list of objects, which I save in the in a pointer list of the Base class:</p>
  
  <pre><code>vector&lt;Base*&gt; listA;
  
  new Base(&amp;listA);
  new A(&amp;listA);
  new B(&amp;listA);
  </code></pre>
  
  <p>These objects I then want to copy in a second list with the same classes (same order), but which might have different values.</p>
  
  <pre><code>for (int i = 0; i &lt; (int)listA.size(); i++)
  {
      (*listA[i]) = (*listB[i]);
  }
  </code></pre>
  
  <p>However c++ is not able to do that. Because the list has the type Base*, dereferencing creates an object of type Base. Therefore the assignment operator= of the Base class is called instead of the correct one from the derived class. How can I fix this?</p>
  
  <p>Or how can I tell c++ to use the right operator? Maybe by some isinstanceof-function?</p>
  
  <p>For a full sample see:</p>
  
  <pre><code>int main()
  {
      vector&lt;Base*&gt; listA;
  
      new Base(&amp;listA);
      new A(&amp;listA);
      new B(&amp;listA);
  
      vector&lt;Base*&gt; listB;
  
      new Base(&amp;listB);
      new A(&amp;listB);
      new B(&amp;listB);
  
  
      for (int i = 0; i &lt; (int)listA.size(); i++)
      {
          (*listA[i]).test();
      }
      for (int i = 0; i &lt; (int)listA.size(); i++)
      {
          (*listA[i]) = (*listB[i]);
      }
  }
  </code></pre>
  
  <p>Which outputs:</p>
  
  <pre><code>Base
  A
  B
  Base=
  Base=
  Base=
  </code></pre>