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)
?
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:
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
andDerived
a size of1
, but this is not mandatory. It would be acceptable if theBase
had size 1729 andDerived
had size 2875.Interesting question. I have an example where a derived class with an extra field is the same size as an empty base class. (This should be a comment but is much too large; please accept one of the other answers, although upvotes are welcome if it's interesting.)
Consider this trivial C++ program:
What would you expect the output to be, if
sizeof(int)
is 4? Perhaps something like:?
My compiler - Embarcadero C++ Builder 2010 - gives the output:
In other words, adding an extra field in the derived class does not make the derived class bigger.
There is some insight into why with the help file topic on the compatibility option Zero-length empty base class.
It appears that the size of a class with default compiler settings for this compiler is 8 bytes, not one, and in fact changing this setting for this code example has no effect.
You may also find this article on base class sizes and the above optimization interesting. It discusses why classes must have a size of at least one byte, what the optimization does, and delves into representation of member functions etc too:
Please read the article for the full context of that quote.
From 5.3.2 [expr.sizeof]
From 1.8 [intro.object]
and a note:
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 thatsizeof(Derived) >= sizeof(Base)
!Now gcc compiler would give "size>0" for the both the objects created by Base and Derived classes. gcc compiler just provides the presence of address for the objects to the user.
My present gcc compiler showed the sizeof objects of both Base and Derived to be same.