title: How does C++ know which element in vector<Base*> is Derived*?
body: <p>How does C++/the compiler know in the code below when to execute the right piece of code? And how is this stored (behind the scenes)? My vector contains <code>Base*</code> but there must be some extra information somewhere, right?</p>
  <p>The <a href="https://repl.it/@DennisJM/DeepPeachpuffComments#main.cpp" rel="nofollow noreferrer">compiling code</a> which is the same as this:</p>
  <pre><code>class Base {
      public:
          Base()=default;   
          virtual void DerivedOrBase() { std::cout &lt;&lt; &quot;Base\n&quot;; }
  };
  
  class Derived : public Base {
      public:
          Derived()=default;   
          void DerivedOrBase() override { std::cout &lt;&lt; &quot;Derived\n&quot;; }
  };
  
  int main()
  {
      std::vector&lt;Base*&gt; myVector;
      myVector.push_back(new Base());
      myVector.push_back(new Base());
      myVector.push_back(new Base());
      myVector.push_back(new Derived());
      
      for(auto p : myVector) p-&gt;DerivedOrBase();
  
      return 0;
  }
  </code></pre>