Basically it is a follow up of this question..
When I look into the Standard docs I found this..
In Classes 9.3,
Complete objects and member subobjects of class type shall have nonzero size.96) ...
Yeah, true.. But,
96)Base class subobjects are not so constrained.
So, when I looked into Stroustrup's FAQ, there is an example as
void f(X* p)
{
void* p1 = p;
void* p2 = &p->a;
if (p1 == p2) cout << "nice: good optimizer";
}
My question is I couldn't understand how it is an optimization and also why base classes are allowed to have zero size?
Base classes cannot have zero size. Only base class subobjects can. Meaning the base part of the derived object.
If the base class is empty, you will never need to have the base class object's or any of its members' address (independent of the derived class objects's address, that is), so it is legal to optimize its size away.
That saves you (at least) one byte of memory (can be more due to memory alignment rules), which can add up to significant savings if you have millions of such objects in your app on a memory-constrained platform.
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