0
Why is the sizeof an empty class is not zero in c++?
define an empty class and print the size of class using sizeof operator. the result is not zero.
1 Answer
+ 3
Its a one instead of a zero, as perhaps even without existing members one may wish to create instances of a class and use methods containing constant function codes. Eg:
class A{void Num();};
void A::Num(){cout<<5<<endl;};
int main()
{
A number;
number.Num();
// I don't think this code is invalid
// as the rules allow such a definition.
}
Now, since A has no members it should have a size of 0, but practically, instances of A must be stored in memory, and using a large size is not necessary. So perhaps the compiler uses the smallest unit of memory (byte) to store objects of such a class so that instances can be stored and referenced.