title: How is the size of a C++ class determined?
body: <p><strong>Summary</strong>: How does the compiler statically determine the size of a C++ class during compilation?</p>
  
  <p><strong>Details</strong>: </p>
  
  <p>I'm trying to understand what the rules are for determining how much memory a class will use, and also how the memory will be aligned.</p>
  
  <p>For example the following code declares 4 classes.  The first 2 are each 16 bytes.  But the 3 is 48 bytes, even though it contains the same data members as the first 2.  While the fourth class has the same data members as the third, just in a different order, but it is 32 bytes.</p>
  
  <pre><code>#include &lt;xmmintrin.h&gt;
  #include &lt;stdio.h&gt;
  
  class TestClass1 {
    __m128i vect;
  };
  
  class TestClass2 {
    char buf[8];
    char buf2[8];
  };
  
  class TestClass3 {
    char buf[8];
    __m128i vect;
    char buf2[8];
  };
  
  class TestClass4 {
    char buf[8];
    char buf2[8];
    __m128i vect;
  };
  
  
  TestClass1 *ptr1;
  TestClass2 *ptr2;
  TestClass3 *ptr3;
  TestClass4 *ptr4;
  int main() {
    ptr1 = new TestClass1();
    ptr2 = new TestClass2();
    ptr3 = new TestClass3();
    ptr4 = new TestClass4();
    printf("sizeof TestClass1 is: %lu\t TestClass2 is: %lu\t TestClass3 is: %lu\t TestClass4 is: %lu\n", sizeof(*ptr1), sizeof(*ptr2), sizeof(*ptr3), sizeof(*ptr4));
    return 0;
  }
  </code></pre>
  
  <p>I know that the answer has something to do with alignment of the data members of the class.  But I am trying to understand exactly what these rules are and how they get applied during the compilation steps because I have a class that has a <code>__m128i</code> data member, but the data member is not 16-byte aligned and this results in a segfault when the compiler generates code using <code>movaps</code> to access the data.</p>