c++compiler-optimizationbase-classempty-class

Why can empty base classes have a zero size?


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?


Solution

  • Base classes cannot have zero size. Only base class subobjects can. Meaning the base part of the derived object.