Wednesday, 13 August 2014

Size of the object created for the empty class

 
What will be the output of following program?

#include<cstdio>

class empty
{
};

class subclass : public empty
{
}


int main()
{
    empty e;
    printf("Size of object created for empty class :: %ld",sizeof(e));
}


Answer


 Size of object created for empty class :: 1

Reason



Why size is not zero but 1?

Size is not zero. It is 1 by default. It is mandtory defined by standard to
keep the size of the object of empty class as 1. This is because to differentiate
the two differnt object created for that class. They will differentiate the two different classes with the memory address.


Size of derived while inherting the empty class

#include<cstdio>

class empty
{
};

class subclass : public empty
{

};        


int main()
{
    empty e;
    printf("Size of object created for empty class :: %ld",sizeof(e));
    subclass s;
    printf("\nSize of object created for derived class inherited to empty class:: %ld",sizeof(s));
   
}

Answer:


Size of object created for empty class :: 1
Size of object created for derived class inherited to empty class ::1

Reason:


Why size of object with inherited class also 1 instead of 2?

Actually nothing will be stored in the empty classes. The 1 byte is allocated to uniquely refer the object in the program. So 1 byte is required. There will be one memory address for the one byte and we can uniquely identify the object in the program.


Thanks to http://www.geeksforgeeks.org/ for intiating this idea