Click to See Complete Forum and Search --> : A question regarding the size of a class.
dullboy
February 13th, 2008, 11:34 AM
Say we have a class defined as,
class c
{
char c1;
char c2;
int i1;
int i2;
char *ptr;
static int mem;
};
What is the size of the class c on a 32 bit processor? Here is what I think.
char c1: 1 byte
char c2: 1 byte
int i1: 4 bytes
int i2: 4 bytes
char* ptr: 4 bytes
static int mem: 4 bytes
Totally, 18 bytes. Am I right? Thanks for your inputs.
laserlight
February 13th, 2008, 11:40 AM
I do not think the static member will be counted. There may also be padding after the two char members (adding another 2 bytes), making it 4 + 4 + 4 + 4 = 16 bytes.
dullboy
February 13th, 2008, 12:09 PM
Thanks for your response! Why will the static member NOT be counted? As for padding, why isn't there padding for each of c1 and c2? Thanks for your inputs.
I do not think the static member will be counted. There may also be padding after the two char members (adding another 2 bytes), making it 4 + 4 + 4 + 4 = 16 bytes.
laserlight
February 13th, 2008, 12:16 PM
Why will the static member NOT be counted?
According to the C++ Standard, "a static data member is not part of the subobjects of a class".
As for padding, why isn't there padding for each of c1 and c2?
Since they are adjacent, together they can fit in the space of an int.
TheCPUWizard
February 13th, 2008, 12:20 PM
Since they are adjacent, together they can fit in the space of an int.
Padding is very much implementation dependant. The compiler could (but probably would not) pad between the char fields. The compiler could (and quite probably would) pad after the characters but before the int in order to have a 32 bit integer properly aligned.
As far as the static, think of it this way. You create 1000 instances of the object, there is still only one copy of the static data (that is the very definition). Therefore it is not part of the size of an instance.
dullboy
February 13th, 2008, 02:15 PM
Thanks for you guys' help! Now I understand the size of the class could be 16 or 20 bytes depending on the compiler.
kirants
February 13th, 2008, 07:14 PM
And don't be fooled that the size of the class below is 0 :)
class A
{
}
MikeAThon
February 13th, 2008, 08:16 PM
... And that you can change the way that the compiler packs the class's structure. For example, in Microsoft's compiler:
struct st1
{
char c;
int i;
};
#pragma pack ( push )
#pragma pack ( 1 )
struct st2 /* identical to st1 */
{
char c;
int i;
};
#pragma pack( pop )
void main()
{
cout << "Size of st1 :" << sizeof(st1) << endl;
cout << "Size of st2 :" << sizeof(st2) << endl;
}
Output (untested):
Size of st1 : 8
Size of st2 : 5
Mike
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.