This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: sizeof empty class


On 8 April 2010 05:01, ranjith kumar <ranjithproxy@gmail.com> 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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]