Is C++ allowed to increase the derived class size if there're no new member variables compared to the base class?

c++, inheritance, language-lawyer, sizeof

Solution

From 5.3.2 [expr.sizeof]

When applied to a class, the result [of `sizeof`] is the number of bytes in an object of that class including any padding required for placing objects of that type in an array. The size of a most derived class shall be greater than zero (1.8).

From 1.8 [intro.object]

Unless it is a bit-field (9.6), a most derived object shall have a non-zero size and shall occupy one or more bytes of storage. Base class sub-objects may have zero size. An object of POD type (3.9) shall occupy contiguous bytes of storage.

and a note:

The actual size of a base class subobject may be less than the result of applying sizeof to the subobject, due to virtual base classes and less strict padding requirements on base class subobjects.

Put these together and I think what it's telling you is that you have no guarantees whatsoever as to what `sizeof` might tell you, other than the result will be greater than zero. In fact, it doesn't even seem to guarantee that `sizeof(Derived) >= sizeof(Base)`!

Problem

Suppose I have a base class with some member variables and no virtual functions: ``` class Base { int member; }; ``` and a derived class that derives in a non-virtual way from `Base` and has no new member variables an again no virtual functions: ``` class Derived : Base { }; ``` Obviously `sizeof(Derived)` can't be smaller than `sizeof(Base)`. Is `sizeof(Derived)` required to be equal to `sizeof(Base)`?

Original source