Thursday, April 9, 2015

Why is the size of an empty class not zero?

To ensure that the addresses of two different objects will be different. For the same reason, new always returns pointers to distinct objects. Consider:
There is an interesting rule that says that an empty base class need not be represented by a separate byte:
This optimization is safe and can be most useful. It allows a programmer to use empty classes to represent very simple concepts without overhead. Some current compilers provide this “empty base class optimization”.

Moreover, “empty base class optimization” is no longer an optional optimization but a mandatory requirement on class layout as of C++11. Go beat up on your compiler vendor if it does not implement it properly.

No comments:

Post a Comment