title: Why are classes with virtual functions aligned differently than classes without?
body: <p>Inspired by this <a href="https://www.youtube.com/watch?v=iLiDezv_Frk" rel="nofollow">cppcon talk by Richard Powell</a> I have created the following code snippet to fool around:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using std::cout;
  using std::endl;
  
  struct erdos
  {
    void who()
    {
      cout &lt;&lt; "erdos" &lt;&lt; endl;
    }
    float f1;
    float f2;
  };
  
  struct fermat : public erdos
  {
    float f3;
  };
  
  struct fermat2 : public fermat
  {
    float f4;
  };
  
  struct fermat3 : public fermat2
  {
    float f5;
  };
  
  int main(void)
  {
    erdos e;
    cout &lt;&lt; "sizeof(e)" &lt;&lt; sizeof(e) &lt;&lt; endl;
    fermat f;
    cout &lt;&lt; "sizeof(f)" &lt;&lt; sizeof(f) &lt;&lt; endl;
    fermat2 f2;
    cout &lt;&lt; "sizeof(f2)" &lt;&lt; sizeof(f2) &lt;&lt; endl;
    fermat3 f3;
    cout &lt;&lt; "sizeof(f3)" &lt;&lt; sizeof(f3) &lt;&lt; endl;
    cout &lt;&lt; "sizeof(void*)" &lt;&lt; sizeof(void*) &lt;&lt; endl;
    cout &lt;&lt; "sizeof(float)" &lt;&lt; sizeof(float) &lt;&lt; endl;
    return 0;
  }
  </code></pre>
  
  <p>which would print:</p>
  
  <pre><code>sizeof(e)8
  sizeof(f)12
  sizeof(f2)16
  sizeof(f3)20
  sizeof(void*)8
  sizeof(float)4
  </code></pre>
  
  <p>After adding <code>virtual</code> to <code>who()</code> I get this</p>
  
  <pre><code>sizeof(e)16
  sizeof(f)24
  sizeof(f2)24
  sizeof(f3)32
  sizeof(void*)8
  sizeof(float)4
  </code></pre>
  
  <p>Now, adding the size of <code>void*</code> to the struct is straightforward but why would there be this padding (which is also mentioned by Richard in his talk) in virtual case and not in non-virtual case?</p>
  
  <pre><code>sizeof(e)16 - 8 = 8 
  sizeof(f)24 - 8 = 16 but is in fact 12 (padding 4)
  sizeof(f2)24 - 8 = 16 matches
  sizeof(f3)32 - 8 = 24 but is in fact 20 (padding 4)
  </code></pre>
  
  <p>I've tested it with gcc 5.3.0 and clang 3.7.1 on Ubuntu 14.04 64 bit</p>