-4

I have this

class Empty {};  // Empty class

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

On my machine, sizeof(Derived); is 8, why? Isn't it supposed to be 1 because it only has 1 char in it?

When I remove the virtual inheritance, sizeof(Derived); is 1.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
  • 1
    Uh the compiler does it. Can you clarify the question? – Flexo May 30 '16 at 15:06
  • 1
    What's the result and what do you expect and why? At least show some effort solving that question yourself! – Ulrich Eckhardt May 30 '16 at 15:07
  • 1
    did you read any [documentation](http://en.cppreference.com/w/cpp/language/sizeof)? What is it that is unclear? – default May 30 '16 at 15:07
  • 1
    You might want to read up on exactly what [virtual inheritance](http://stackoverflow.com/questions/21558/in-c-what-is-a-virtual-base-class) is and how it works. Virtual inheritance requires some extra book keeping, which is why it results in a larger object size. – Cornstalks May 30 '16 at 15:11
  • 1
    ...and if you're on a 64bit machine, it becomes 16, same reason: pointer and padding. – deviantfan May 30 '16 at 15:15
  • You might want to read up on *alignment* and *structure padding*. On some platforms, the compiler pads to 8-byte boundaries. – Thomas Matthews May 30 '16 at 17:13

1 Answers1

6

On my machine, sizeof(Derived); is 8, why?

Because that's what the compiler chose. The representation of the object may need more memory due to the virtual base. In a typical implementation, there will be a "virtual table pointer" within the object.

Isn't it supposed to be 1 because it only has 1 char in it?

No. The size of an object is not "supposed to be" the sum of the size of it's members.

eerorika
  • 232,697
  • 12
  • 197
  • 326