Why is the sizeof an empty class is not zero in c++? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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.

15th Jan 2018, 4:21 PM
Irfan
Irfan - avatar
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.
15th Jan 2018, 6:42 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar