Monday, June 1, 2009

C++ Questions

1.What is the class size. a.Empty(without members or Virtual fns) b.Non Empty(with membersor Virtual fns)...

Description:

a.Is 1 because class/struct cannot be 0 bytes, because each instance of theclass/struct must have its own unique address, the compiler just adds a byte for padding.
b. Normally class size depends on its class variables size+vptrs size+padding done by compiler...

check below classes

1.//class size same as variables size (same as int size)
#include
class MyCLass
{
int i;
};

2.//class size same as variables size (its size is 8 which more than members size)
#include
class MyCLass
{
int i;
char a;
}

this is because the default allocation of memory by compiler...might be different

to make the above class to show the size same as members size use below one

#include
#pragma pack(1)
class MyCLass
{
int i;
char a;
}

#pragma pack(1) line specifies to compiler to allocate default allocation size to 1byte.that clears our problem.