title: What is a "virtual thunk" to a virtual function that inherits from a virtual base class?
body: <p>Something went wrong when I try to access the memory layout of a derived class object which inherits from a virtual base class.<br>
  Programming environment: GNU/Linux 3.19.0-32-generic, x86_64<br>
  Compiler: gcc 4.8.4</p>
  
  <pre><code>//virtual base class
  class Base {
  public :
      virtual void f() {
          cout &lt;&lt; "Base::f()" &lt;&lt; endl;
      }
  private:
      long x;
  };
  
  //derived class
  class Derived : public virtual Base {
  public:
      virtual void f() {
          cout &lt;&lt; "Derived::f()" &lt;&lt; endl;
      }
  private:
      long y;
  };
  
  int main() {
      typedef void (*FUNC)(void);
      Derived d;
  
      //In my machine, sizeof(long) == sizeof(pointers). My code below is neither portable nor concise. You can just read the annotation.
  
      //dereference the first element of the first virtual function table(equals to *(vptr1-&gt;slot[0]))
      cout &lt;&lt; hex &lt;&lt; *((long*)*((long*)(&amp;d) + 0) + 0) &lt;&lt; endl;
      ((FUNC)*((long*)*((long*)(&amp;d) + 0) + 0))();//invoke Derived::f()
  
      //dereference the first element of the second virtual function table(equals to *(vptr2-&gt;slot[0]))
      cout &lt;&lt; hex &lt;&lt; *((long*)*((long*)(&amp;d) + 2) + 0) &lt;&lt; endl;
      ((FUNC)*((long*)*((long*)(&amp;d) + 2) + 0))();//maybe Derived::f()?
  
      return 0;
  }
  </code></pre>
  
  <p>When I run the code, I got "segment fault":</p>
  
  <pre><code>400c12
  Derived::f()
  400c3c
  segment fault
  </code></pre>
  
  <p>So I disassembly the executable file.<br>
  I found the function  &lt;_ZTv0_n24_N7Derived1fEv> in 0x400c3c:</p>
  
  <pre><code>0000000000400c3c &lt;_ZTv0_n24_N7Derived1fEv&gt;:
    400c3c:       4c 8b 17                mov    (%rdi),%r10
    400c3f:       49 03 7a e8             add    -0x18(%r10),%rdi
    400c43:       eb cd                   jmp    400c12 &lt;_ZN7Derived1fEv&gt;
    400c45:       90                      nop
  </code></pre>
  
  <p>Demangle the symbol in my terminal:</p>
  
  <pre><code>&gt; c++filt _ZTv0_n24_N7Derived1fEv
  virtual thunk to Derived::f()
  </code></pre>
  
  <p>Then what is a virtual thunk to Derived::f()?Why is it there?</p>