title: polymorphism in a vector
body: <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  using std::cout;
  using std::cin;
  using std::endl;
  
  class base {
      int data;
  public:
      base(int d = 100) : data(d) {}
      virtual int getData() const {return data;}
  };
  
  class derived : public base {
      int dData;
  public:
      derived(int dd = 32) : base(), dData(dd) {}
      virtual ~derived(){}
      int getData() const {return dData;}
  };
  
  
  
  int main(){
      std::vector&lt;base&gt; vec;
      base A(20);
      derived B(32);
  
      vec.push_back(A);
      vec.push_back(B);
  
      for(unsigned int i=0; i &lt; vec.size(); i++)
          cout &lt;&lt; "vector[" &lt;&lt; i &lt;&lt; "] :" &lt;&lt; vec[i].getData() &lt;&lt; endl;
  
      base * ptr;
      ptr = &amp;A;
      cout &lt;&lt; "Base pointing: " &lt;&lt; ptr-&gt;getData() &lt;&lt; endl;
  
      ptr = &amp;B;
      cout &lt;&lt; "Derived pointing: " &lt;&lt; ptr-&gt;getData() &lt;&lt; endl;
  
  }
  </code></pre>
  
  <p>Above the code,i create a vector which is type of base and put a derived object in it. when i try to read the values i cant get the correct ones. Even though i put 'virtual' statement before the function which has the same name in my classes. But in pointer way there is no problem. </p>
  
  <p>here is the output of code.</p>
  
  <pre><code>vector[0] :20
  vector[1] :100
  Base pointing: 20
  Derived pointing: 32
  </code></pre>