title: Calling a virtual function on a vector of base classes
body: <p>I created some code to reproduce the problem:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include "stdafx.h"
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class A
  {
  protected:
      int m_X;
  public:
      A() { 
          std::cout &lt;&lt; "in A ctor" &lt;&lt; std::endl; 
          m_X = 0;
      }
      virtual void printX(){ std::cout &lt;&lt; "in A " &lt;&lt; m_X &lt;&lt; std::endl; }
  };
  
  class B : public A
  {
  public:
      B() {
          std::cout &lt;&lt; "in B ctor" &lt;&lt; std::endl; 
          m_X = 1;
      }
      virtual void printX(){ std::cout &lt;&lt; "in B " &lt;&lt; m_X &lt;&lt; std::endl; }
  };
  
  class As
  {
  public:
      void AddA( const A &amp;a ){ m_As.push_back( a ); }
      void PrintXs()
      {
          for ( auto a : m_As )
          {
              a.printX();
          }
      }
  private:
      std::vector&lt;A&gt; m_As;
  };
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      As as;
      B b;
      as.AddA( b );
      as.PrintXs();
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>The output of this is:</p>
  
  <p>in A ctor</p>
  
  <p>in B ctor</p>
  
  <p>in A 1</p>
  
  <p>I want "in B 1" instead of "in A 1". I'm sure my understanding of virtual is flawed. How must I change the code to call the B PrintX()? Note that there will be other classes that inherit from A so I really don't want to code a static call.</p>
  
  <p>Thanks.</p>