Possible Duplicate:
C++: What is the size of an object of an empty class?
Why does the following output 1
?
#include <iostream> class Test { }; int main() { std::cout << sizeof(Test); return 0; }
Actually, the standard does not permit objects (or classes) of size 0, this is because that would make it possible for two distinct objects to have the same memory location. This is the reason behind the concept that even an empty class must have a size at least 1. It is known that size of an empty class is not zero.
So, according to the C standard, it was decided to keep the size of the empty structure to zero. In C++, the Size of an empty structure/class is one byte as to call a function at least empty structure/class should have some size (minimum 1 byte is required ) i.e. one byte to make them distinguishable.
An Empty class's object will take only one byte in the memory; since class doesn't have any data member it will take minimum memory storage.
Size of an empty class is not zero. It is 1 byte generally.
The standard does not allow objects (and classes thereof) of size 0, since that would make it possible for two distinct objects to have the same memory address. That's why even empty classes must have a size of (at least) 1.
To ensure that the addresses of two different objects will be different. For the same reason, "new" always returns pointers to distinct objects.
See Stroustrup for complete answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With