sizeof empty class

Fri Apr 9 05:03:00 GMT 2010

On 8 April 2010 05:01, ranjith kumar <> wrote:
> 1) What is the size of an an empty class? On my machine it is showing 1

Assuming you mean in C++...

    struct Empty {};

Different objects of the same type must have different addresses, so
to allow for arrays, sizeof(Empty) must be > 0.

    Empty a[2];
    a != a+1 <=> (Empty*)((char*)a + sizeof(Empty))

There is, however, an "empty base class" optimization that the
compiler will try to perform.

    struct D : Empty {};

You will probably find that sizeof(D) == sizeof(Empty), rather than
sizeof(D) == 2*sizeof(Empty).

But remember that, for a given type, different object <=> different
address applies to empty base classes too:

    struct D2 : D, Empty {};

Because D2 contains 2 sub-objects of type Empty (one a base of D2, one
a base of D), sizeof(D2) >= 2*sizeof(Empty) >= 2.

~ Scott McMurray

More information about the Gcc-help mailing list