1

I was going through some of the c++ puzzles. And I have seen this question.

#include <iostream>
using namespace std;

class Empty
{};

class Derived1 : public Empty
{};

class Derived2 : virtual public Empty
{};

class Derived3 : public Empty
{    
    char c;
};

class Derived4 : virtual public Empty
{
    char c;
};

class Dummy
{
    char c;
};

int main()
{
    cout << "sizeof(Empty) " << sizeof(Empty) << endl;
    cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
    cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
    cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
    cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;    
    cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;

    return 0;
}

When I run the code.The results are found to be:

sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8
sizeof(Dummy) 1

Can some one explain why the sizeof(Derived2) and sizeof(Derived4) are 4 and 8 respectively?

Thanks.

starkk92
  • 5,754
  • 9
  • 43
  • 59
  • 1
    If the size of an empty class was zero, you'd be able to have arrays with each index with a size of zero.. That's simply not possible.. – Brandon Apr 07 '14 at 18:08
  • 3
    Dupes [here](https://stackoverflow.com/questions/621616/c-what-is-the-size-of-an-object-of-an-empty-class), [here](https://stackoverflow.com/questions/18164702/size-of-a-empty-class-derived-virtual-class?rq=1), [here](https://stackoverflow.com/questions/20163117/why-sizeofderived4-is-8-byte-i-think-it-should-be-5-bytes?rq=1); and I'm sure there are many more. Did you bother searching at all, or even looking through the suggested matches when you were posting this question? – Praetorian Apr 07 '14 at 18:09
  • Argh. That makes completely sense!!! I thought it would be 0, but now, after reading these 'here, here', here' posted by @Praetorian it made completely sense. This one byte contains possibly garbage! – Grzegorz Apr 07 '14 at 18:13
  • Inside C++ Object Model states that a 0-sized class cannot have an address. – xis Apr 07 '14 at 19:32

0 Answers0