title: Virtual dispatch implementation details
body: <p>First of all, I want to make myself clear that <em>I do understand that there is no notion of vtables and vptrs in the C++ standard</em>. However I think that virtually all implementations implement the virtual dispatch mechanism in pretty much the same way (correct me if I am wrong, but this isn't the main question). Also, I believe <em>I know how virtual functions work</em>, that is, I can always tell which function will be called, I just need the implementation details.</p>
  
  <p>Suppose someone asked me the following:<br>
   "You have base class B with virtual functions v1, v2, v3 and derived class D:B which overrides functions v1 and v3 and adds a virtual function v4. Explain how virtual dispatch works". </p>
  
  <p>I would answer like this:<br>
  For each class with virtual functions(in this case B and D) we have a separate array of pointers-to-functions called vtable.<br>
  The vtable for B would contain</p>
  
  <pre><code>&amp;B::v1
  &amp;B::v2
  &amp;B::v3
  </code></pre>
  
  <p>The vtable for D would contain</p>
  
  <pre><code>&amp;D::v1
  &amp;B::v2
  &amp;D::v3
  &amp;D::v4 
  </code></pre>
  
  <p>Now the class B contains a member pointer vptr. D naturally inherits it and therefore contains it too. In the constructor and destructor of B B sets vptr to point to B's vtable. In the constructor and destructor of D D sets it to point to D's vtable.<br>
  Any call to a virtual function f on an object x of polymorphic class X is interpreted as a call to x.vptr[f's position in vtables]</p>
  
  <p>The questions are:<br>
  1. Do I have any errors in the above description?<br>
  2. How does the compiler know f's position in vtable (in detail, please)<br>
  3. Does this mean that if a class has two bases then it has two vptrs? What is happening in this case? (try to describe in a similar manner as I did, in as much detail as possible)<br>
  4. What's happening in a diamond hierarchy with A on top B,C in the middle and D at the bottom? (A is a virtual base class of B and C)</p>
  
  <p>Thanks in advance.</p>