title: Virtual destructors and deleting objects with multiple inheritance... How does it work?
body: <p>First, I understand why <code>virtual</code> destructors are needed in terms of single inheritance and deleting an object through a base pointer. This is specifically about multiple inheritance and the reason behind <em>why</em> this works. This question came up in one of my university classes, and no one (including the professor) was sure why this worked:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  struct A
  {
      virtual ~A()
      {
          std::cout &lt;&lt; "~A" &lt;&lt; std::endl;
      }
      int memberA;
  };
  
  struct B
  {
      virtual ~B()
      {
          std::cout &lt;&lt; "~B" &lt;&lt; std::endl;
      }
      int memberB;
  };
  
  struct AB : public A, public B
  {
      virtual ~AB()
      {
          std::cout &lt;&lt; "~AB" &lt;&lt; std::endl;
      }
  };
  
  int main()
  {
      AB* ab1 = new AB();
      AB* ab2 = new AB();
  
      A* a = ab1;
      B* b = ab2;
  
      delete a;
      delete b;
  }
  </code></pre>
  
  <p>The output for this is:</p>
  
  <blockquote>
    <p><code>~AB</code><br>
    <code>~B</code><br>
    <code>~A</code><br>
    <code>~AB</code><br>
    <code>~B</code><br>
    <code>~A</code></p>
  </blockquote>
  
  <p>How does the compiler know how to call <code>A</code>'s and <code>B</code>'s destructor when deleting <code>a</code> or <code>b</code>? Specifically, how is the memory for <code>AB</code> laid out (particularly it's virtual function table), such that the <code>A</code> and <code>B</code> destructors can be called?</p>
  
  <p>My professor was suggesting that memory would be laid out (something) like this:</p>
  
  <pre><code>    AB
  +---------+              +----+
  |  A VFT  | - - - - - -&gt; | ~A |
  +---------+              +----+
  | memberA |
  +---------+              +----+
  |  B VFT  | - - - - - -&gt; | ~B |
  +---------+              +----+
  | memberB |
  +---------+
  
  // I have no idea where ~AB would go...
  </code></pre>
  
  <p>We're all curious how these destructors are actually laid out in memory and how calling <code>delete</code> on either <code>a</code> or <code>b</code> results in all the destructors being properly called. It makes sense that deleting a base object works in single inheritance (because there's a single virtual function table to work with), but apparently I'm not understanding things correctly because I can't take my understanding of the single inheritance version and apply it to this multiple inheritance example.</p>
  
  <p>So how does this work?</p>