In the tutorial at this link, there is the following statement:
The part in question is the bold part. The author first says the the size of the first code example class is 24 bytes, and then in the second code example, he changed the order of the members to put the char variable last, says the size of this class is 20 bytes, and then follows that up immediately with a statement saying it is storing the char in one of the slots in "the hole in the extra four bytes". Now, I don't know about you, but that doesn't really make any sense to me. If the char, even after putting it at the end of the class instead of the beginning, is still getting 4 bytes of memory allocated for it, of which only 1 byte is actually being used, then why has the class become only 20 bytes now instead of 24 (if the author is correct, I haven't tested it yet)? I also don't understand why the char would have 4 bytes allocated for it instead of one, even if its followed by an int definition in the class. To me, both versions of the class should allocate 21 bytes for an object of that class, not 24.<2>Order of data members The order in which one specifies data members also alters the size of the class.
The size of this class is 24 bytes. Even though char c will consume only 1 byte, 4 bytes will be allocated for it, and the remaining 3 bytes will be wasted (holes). This is because the next member is an int, which takes 4 bytes. If we don't go to the next (4th) byte for storing this integer member, the memory access/modify cycle for this integer will be 2 read cycles. So the compiler will do this for us, unless we specify some byte padding/packing.Code:class C { char c; int int1; int int2; int i; long l; short s; };
If I re-write the above class in different order, keeping all my data members like below:
Now the size of this class is 20 bytes.Code:class C { int int1; int int2; int i; long l; short s; char c; };
In this case, it is storing c, the char, in one of the slots in the hole in the extra four bytes.
Maybe someone would care to explain a little better than it was in the tutorial?
Thanks in advance.