What are these values on your system?
Does that tell you anything ? :)
DP
It's different! To make it simpler, the Data2 will only contains an
int and a bool, the data2size is 8 and membersize is 5. I am fine if
using 5 for output. The sizeof(ClassType) is bad, is it? Thanks a lot.
zl2k
You're onto something, but your conclusion is wrong I think. What I
wanted to show you was that the Data2 class may very well be larger
than the sum of its members (sizeof returns the number of bytes of the
object). So what are those extra bytes?
Put simply, they are "padding" inserted by the compiler so that it may
access the members of the class more efficiently. This is commonly
referred to as _alignment_. Naturally when you take the address of the
object and interpret it as a char*, you will expose the padding bytes.
Data2 possible object layout:
[ 0 ][ 1 ][ 2 ][ 3 ][ 4 ][ 5 ][ 6 ][ 7 ]
[ int (4 bytes) ][bool][ padding ]
The padding could be set to a special value by the compiler to
correspond to "uninitialized memory", or it could simply be garbage.
Hence, your binary file will have bytes with an unspecified value
written to it.
Class member alignment may vary depending on architecture and compiler
version, and even the settings of the compiler. This is covered by
James Kanze's post.
DP
sizeof() as the writting, I'll be fine. But I am still facing risk if
sizeof(ClassType). The conclusion is draw is telling the system the
exact length of the ClassType "manually". Hope I get it right. Thanks
again and this forum helps me a lot.