title: sizeof class with int , function, virtual function in C++?
body: <p>This is an online C++ test question, which has been done. </p>
  
  <pre><code>#include&lt;iostream&gt;
  using namespace std; 
  class A
  {
  
  };
  class B
  {
  int i; 
  }; 
  
  class C
  {
  void foo();
  };
  class D
  {
  virtual void foo();
  };
  
  class E
  {
  int i ; 
      virtual void foo();
  };
  class F
  {
  int i; 
      void foo();
  };
  class G
  {
      void foo();
      int i;
      void foo1();
  };
  
  class H
  {
      int i ;
      virtual void foo();
      virtual void foo1();
  };
  int main()
  {
  cout &lt;&lt;"sizeof(class A) : " &lt;&lt; sizeof(A) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class B) adding the member int i : " &lt;&lt; sizeof(B) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class C) adding the member void foo() : " &lt;&lt; sizeof(C) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class D) after making foo virtual : " &lt;&lt; sizeof(D) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class E) after adding foo virtual , int : " &lt;&lt; sizeof(E) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class F) after adding foo  , int : " &lt;&lt; sizeof(F) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class G) after adding foo  , int : " &lt;&lt; sizeof(G) &lt;&lt; endl ;
  G g;
  cout &lt;&lt;"sizeof(class G) after adding foo  , int : " &lt;&lt; sizeof(g) &lt;&lt; endl ;
  cout &lt;&lt;"sizeof(class H) after adding int 2 virtual " &lt;&lt; sizeof(H) &lt;&lt; endl ;
  return 0; 
  }
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>sizeof(class A) : 1
  sizeof(class B) adding the member int i : 4
  sizeof(class C) adding the member void foo() : 1
  sizeof(class D) after making foo virtual : 8
  sizeof(class E) after adding foo virtual , int : 16
  sizeof(class F) after adding foo  , int : 4
  sizeof(class G) after adding foo   , unsigned int : 4
  sizeof(class g) after adding foo  , unsigned int : 4
  sizeof(class H) after adding int 2 virtual 16
  </code></pre>
  
  <p>My questions: </p>
  
  <p>Why <code>siszeof(A)</code> is 1 and <code>sizeof(C)</code> is 1 too ? </p>
  
  <p>Why <code>siszeof(H)</code> is 16 but <code>sizeof(G)</code> is 4 ? </p>
  
  <p>Why <code>siszeof(E)</code> is 16 but <code>sizeof(F)</code> is 4 ? </p>
  
  <p>Why <code>siszeof(D)</code> is 8 but <code>sizeof(E)</code> is 16 ?  </p>
  
  <p>My guess: </p>
  
  <p>A virtual function is a pointer with 8 bytes. 
  But, I do not know why <code>E</code> size is 16 ? 
  Adding a function to an empty class does not change its size ? </p>
  
  <p>Any help is appreciated. </p>
  
  <p>thanks</p>