title: Calling subclass methods from superclass in a vector C++
body: <p>I am trying to add a number of subclassed elements into a vector, iterate through them calling a overridden method and want it to call the overridden method where possible. However I have found that it appears to only be calling the superclass method.</p>
  
  <p>I learnt Java and am unsure why it is doing this in C++. I have tried rewriting the code using a vector of pointers of the superclass and casting the pointer of the subclass to the superclass. Accessing this through pointers then works.</p>
  
  <p>Ideally I dont want to have to put a list of pointers into the vector since then I have to manually delete each one (I believe?) to stop memory leaks since I will be creating the objects with new so they persist past the method call to add them into the vector.</p>
  
  <p>Is there a better way to do this or am I stuck to using pointers and calling delete on the created objects when the parent class is unneeded? Preferably the vector would be a list of class X rather than a list of pointers of class X</p>
  
  <p>My structure is:</p>
  
  <pre><code>class a { vector vec of class X,
      method to create and add an instance of X into vector vec,
      method to create and add an instance of Y into vector vec }
  class X { talk() }
  class Y : public X { talk() }
  </code></pre>
  
  <p>Code to demonstrate what I ideally want to do, but showing its broken by only calling the superclass method:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class A {
    public:
      virtual void talk() { printf("A\n"); }
  };
  
  class B: public A {
    public:
        void talk() { printf("B\n"); }
  };
  
  int main(void) {
      std::vector&lt;A&gt; vec;
      std::vector&lt;A*&gt; vec2;
      A a;
      B b;
      a.talk();
      b.talk();
  
      vec.push_back(a);
      vec.push_back(b);
      vec2.push_back(&amp;a);
      vec2.push_back(&amp;b);
  
      for(int i = 0; i &lt; vec.size(); i++) {
          vec[i].talk();
          vec2[i]-&gt;talk(); //bad but short for example
      }
  
  }
  </code></pre>