Is C++ allowed to increase the derived class size if there're no new member variables compared to the base class?
Solution 1:
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)
!
Solution 2:
There is no such requirement.
The only relevant part of the language I can think of is that every object, whether complete or not, and whether most-derived or not, has an identity, which is given by the pair of its address and its type. Cf. C++11 1.8/6:
Two objects that are not bit-fields may have the same address if one is a subobject of the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they shall have distinct addresses.
So both the most-derived object and the base subobject of your example must have distinct identities.
It would certainly make sense for a compiler to give both Base
and Derived
a size of 1
, but this is not mandatory. It would be acceptable if the Base
had size 1729 and Derived
had size 2875.