what is size of empty class and difference between union, structure and class in c++ ?
My idea:
if no static members in them, they should be same because all members are allocated on stack.
If they are all empty, they are same.
if they have static members, it depends the relative location of the members inside them.
right ?
thanks
C++ Standard standard specify's that the size of an Empty class should be Non-Zero.
Usually, it is 1
byte on most systems.
In Bjarne Stroustrup's words, the size is non-zero "To ensure that the addresses of two different objects will be different."
The size is 1
on most systems because the alignment rules don't matter as the entry of the class name is made in symbol table just to obtain an unique address.
For Standerdese fans:
C++03 Standard Section 9: Classes, Para 2:
Complete objects and member subobjects of class type shall have nonzero size.
94)
class == struct
the only difference is that in a struct, all members i.e. ivars and methods are public by default.
static members i.e. variables or methods, are not part of the class/struct in the sense they do not belong to a particular instance. so a sizeof will not include them.
union
is not a class nor struct, Union is used to map a struct to a particular memory layout.
to get the size just do a sizeof()
of an instance variable and you will see.