C++ question

puffpio

Golden Member
Dec 21, 1999
1,664
0
0
I have two calsses

class Date
{
short year;
char month;
char day;
}

class DateTime : Date
{
char hour;
char minute;
char second;
int millisecond;
}

where char is 1 byte, short is 2 bytes, and int is 4 bytes
I was assuming that sizeof(DateTime) would then be 11 bytes...but when I actually called sizeof(DateTime) I got 12 bytes!!
Is there a 1 byte overhead for inherited classes?
A sizeof(Date) is 4...therefore 8 other bytes are in DateTime where is only look like it should be contributing 7
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
You could check this by looking at the addresses of class members (after creating an instance/object of the class), but my guess is the compiler is adding a padding byte between the chars and int so the int will be aligned on a 32-bit boundary.
 

Matthias99

Diamond Member
Oct 7, 2003
8,808
0
0
Originally posted by: DaveSimmons
You could check this by looking at the addresses of class members (after creating an instance/object of the class), but my guess is the compiler is adding a padding byte between the chars and int so the int will be aligned on a 32-bit boundary.

That would be my guess as well. On some platforms, you have to have your variables word-aligned (although not on x86).

There may be a compiler flag you can use that will make it not do that (in case it is vital that your structure be exactly 11 bytes long when you make a big array of them or something).