6

I was testing with the size of base classes and derived classes in C++.

class X {}; 
class Y : public virtual X {}; 
class Z : public virtual X {}; 
class A : public Y, public Z {};

The sizeof each X,Y,Z,A came to 1,8,8,12 respectively. I am not able to understand this. I know the default size of an empty class is 1. So I could understand the sizeof X is 1. I know the size of Y and Z will not be as there will be virtual_pointer added to it. But 8? I dont get this. Can somebody explain?

user1429322
  • 1,266
  • 2
  • 24
  • 38
  • 4
    It's called unspecified behavior: the implementation can do whatever it wants to make the program work correctly, and there is no requirement for the behavior to be documented or even dependable. – DanielKO Oct 01 '13 at 03:38

1 Answers1

2

It depends on the implementation in your compiler. Say, I got 1, 8, 8, 16 on GCC.

For the Y class, it may create a vtable for virtual base X plus 1 byte for the empty class body. After 4-byte alignment, it makes 8 bytes in total.

UPD: Also it may depend on whether you compile for 32 or 64 bit architecture. vtable pointer on a 64bit platform will take 8 bytes, hence the sizes of Y and Z.

So the complete answer on your question depends on the compiler and the target platform.

Karadur
  • 1,226
  • 9
  • 16
  • It's not quite "plus 1 byte for the empty class body", it's "plus 0 bytes, rounded up to the first non-zero multiple of 4". – user541686 Oct 01 '13 at 04:44
  • The size of a derived class should be no less than the size of the base class. The idea was, in the Y class we had 4 bytes of vtable + 1 byte for empty body of the class X (not empty body of Y). Then align 5 bytes and get 8 bytes. Again it also depends on whether we compile for 32 or 64 bit. – Karadur Oct 01 '13 at 04:51
  • 3
    Maybe this isn't what you meant, but an empty class body isn't 1 byte. It's zero bytes. The only thing is that once the entire type of the object is known, the object needs to be at least one byte big, so if it is zero bytes, a single byte is added. But an empty class doesn't contribute any bytes by itself. – user541686 Oct 01 '13 at 04:55
  • 3
    `vtable` should read `vtable` *pointer* throughout this answer. The `vtable` isn't part of an instance of the class, or of its size, but the `vtable` pointer is. – user207421 Oct 01 '13 at 06:05
  • Mehrdad, an empty class, when derived from, can in theory contribute its one byte to the derived class. It's up to the compiler to optimise it out. Also, an 'empty class body' as a concept has no bytes and no size at all. But yes it gets some size when compiled which guaranteed to be at least 1 byte long. – Karadur Oct 01 '13 at 07:59