tags:

views:

77

answers:

3
#include <stdio.h> 

class X 
{
};

class Y
{
     // long x; // case A)
     // X x;    // case B)
};

class Z : public Y, public X
{
};

int main() {
     Z z;
     printf("%d %d %d\n", 
        sizeof(Z), sizeof(Y), (char*)static_cast<X*>(&z) - (char*)&z);
     return 0;
}

Why is the output as follows after uncommenting either case A or case B:

A: 4 4 4
B: 2 1 2

Why is sizeof(Y) != sizeof(Z) in case B), but is equal in case A). Can anyone explain?

+4  A: 

My memory is vague on this, but I think it's because the two X sub-objects of Z (the base class X and Y::x) must have different addresses.

Marcelo Cantos
+1  A: 

Empty classes still are required to have a size of at least 1. But that doesn't mean that they have to impart that size to their sub-classes.

PigBen
A: 

Just a little addition to your code:

#include <stdio.h>

class X
{
};

class Y
{
    // long x; // case A)
    public:
        X x;    // case B)
};

class Z : public Y, public X
{
};

int main() {
    Z z;
    printf("%d %d %d\n", sizeof(Z), sizeof(Y), (char*)static_cast<X*>(&z) - (char*)&z);

    printf("%p %p %p %p\n", &z, static_cast<Y*>(&z), static_cast<X*>(&z), &z.x);

    return 0;
}

In my machine I get:

2 1 1
0x7fff8876fcb0 0x7fff8876fcb0 0x7fff8876fcb1 0x7fff8876fcb0
   ^^Z             ^^Y             ^^X            Z::x

So, the two bytes are taken by X objects. One is the base class, the other is the one present in Y.

nakiya