title: How is dynamic_cast implemented
body: <p>Consider this simple hierarchy:</p>
  
  <pre><code>class Base { public: virtual ~Base() { } };
  class Derived : public Base { };
  </code></pre>
  
  <p>Trying to downcast <code>Base* p</code> to <code>Derived*</code> is possible using <code>dynamic_cast&lt;Derived*&gt;(p)</code>. I used to think <code>dynamic_cast</code> works by comparing the vtable pointer in <code>p</code> to the one in a <code>Derived</code> object.</p>
  
  <p>But what if we derive another class from <code>Derived</code>? We now have:</p>
  
  <pre><code>class Derived2 : public Derived { };
  </code></pre>
  
  <p>In this case:</p>
  
  <pre><code>Base* base = new Derived2;
  Derived* derived = dynamic_cast&lt;Derived*&gt;(base);
  </code></pre>
  
  <p>We still get a successful downcast, even though the vtable pointer in <code>Derived2</code> has nothing to do with a vtable pointer in <code>Derived</code>. </p>
  
  <p>How does it actually work? How can the <code>dynamic_cast</code> know whether <code>Derived2</code> was derived from <code>Derived</code> (what if <code>Derived</code> was declared in a different library)?</p>
  
  <p>I <strong>am</strong> looking for specific details about how this actually works (preferably in GCC, but others are fine too). This question is <strong>not</strong> a duplicate of <a href="https://stackoverflow.com/questions/3314944/how-is-dynamic-cast-typically-implemented">this question</a> (which doesn't specify how it actually works).</p>