need clarification with class memory structure

To my knowledge the size of the object is the sum of all the variables declared in the class which i get correct when i just have a an int as following
class abcd{
int i;
};
int main()
{
abcd a;
cout<<sizeof(a)<<endl;
system("pause");
}
output:
4
Press any key to continue . . .
and when i just have a single character
class abcd{
char ch;
};
output:
1
Press any key to continue . . .
but when i put in both in one class the size of the object should be 5 but what the output shows me is the following
class abcd{
char ch;
int i;
};
output:
8
Press any key to continue . . .
and when we have an empty class the size should be zero but the compiler shows me not zero
class abcd{

};
output:
1
Press any key to continue . . .

Now why is that? why the size of the class is not zero and why is the size of the object 8 when it only has a char and an int which amount to size 5?
Also what is the size of a function? is it zero ??
Last edited on
This is structure padding. Memory can be much more quickly accessed if it falls on memory boundaries. For example, if an int is 4 bytes wide, it can be quickly accessed if its lands on a 4-byte boundary in memory.

So as a speed optimization, the compiler will realign members of a class/struct to put variables on these boundaries.

In your case, what's happening is this:

1 byte: char ch
3 bytes: (padding)
4 bytes: int i

total class size: 8 bytes.



Functions are code, not data, so they do not need to be stored in the class. The memory for a class only needs to record information that is unique in each instance of the class. Since functions are shared by all instances, they only need to exist in memory once and therefore do not add to the size of the class.

It's the same reason why static variables do not increase class size.


Also beware that if you have a polymorphic class there might be additional "hidden" data (for the vtable) that increases the class size. Classes are polymorphic if they have at least one virtual function, or if they have a parent that is polymorphic.
Last edited on
Thanks guys ... appreciate it
Topic archived. No new replies allowed.