It is a simple question. Code first.
struct A {
int x;
};
struct B {
bool y;
};
struct C {
int x;
bool y;
};
In main function, I call
cout << " bool : " << sizeof(bool) <<
"\n int : " << sizeof(int) <<
"\n class A : " << sizeof(A) <<
"\n class B : " << sizeof(B) <<
"\n class C : " << sizeof(C) << "\n";
And the result is
bool : 1
int : 4
class A : 4
class B : 1
class C : 8
Why is the size of class C 8 instead of 5?
Note that this is compiled with gcc in MINGW 4.7 / Windows 7 / 32 bit machine.
The alignment of an aggregate is that of its strictest member (the member with the largest alignment requirement). In other words the size of the structure is a multiple of the alignment of its strictest (with the largest alignment requirement) member.
The size of the structure above will be 16 bytes because 16 is a multiple of 8. In your example the strictest type is int aligning to 4 bytes. That’s why the structure is padded to have 8 bytes. I’ll give you another example:
The size of the structure above is 16. 16 is multiple of 8 (alignment of double in my environment).
I wrote a blog post about memory alignment for more detailed explanation
http://evpo.wordpress.com/2014/01/25/memory-alignment-of-structures-and-classes-in-c-2/