Tuesday, February 14, 2012

What is the size of the empty class in c++?

The size of the empty class is always ONE and not ZERO. This is because of below reasons

1. Every object should have some address location to identify, independent of the no.of member variables in the class. Generally the size of the object is the sum of the member variables in the class. if no data is there, one byte of memory allocated to the object to identify. this will help to not conflicting with other empty objects.

2. One more logical reason is that Some times we will use the sizeof() operator in division operation like X%sizeof(emptyclass) and if the value of empty class is zero , application/program will crash.

See the sample code and result:

using namespace std;
class Empty

int main()
Empty e1,e2;
cout<< "size of e1 is "<<sizeof(e1)<<" address of e1 is "<<&e1<<endl;
cout<< "size of e2 is "<<sizeof(e2)<<" address of e2 is "<<&e2<<endl;

size of e1 is 1 address of e1 is 0x7fffd925bacf
size of e2 is 1 address of e2 is 0x7fffd925bace

No comments:

Popular Posts