Virtual inheritance using empty classes

Can someone please indicate the exact reason for the output of the following C ++ code? The result I got for the code is included in the header comments. What does this have to do with the virtual table and v pointer.

/* sizeof(Empty) 1 sizeof(Derived1) 1 sizeof(Derived2) 8 sizeof(Derived3) 1 sizeof(Derived4) 16 sizeof(Dummy) 1 */ #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; } 
+5
source share
3 answers

First, even a class without members must have a nonzero size. The standard insists on this. Otherwise, pointer arithmetic and arrays will not work, since an array of a class of zero size will have all its elements in the same place!

The fact that other sizes are different may well be caused by a v-table. But this is not necessarily stated in the standard, so this is a manifestation of how your compiler deals with things.

We also note that polymorphism requires at least one virtual method, which must be defined in the base class. This means that sizeof(Derived1) is the same size as the base class.

+3
source

The difference in size is due to vptr added by the compiler.

sizeof(Derived1) = 1 , this is because, according to C ++ standards, an empty class always takes 1 byte of memory.

sizeof(Derived2) = 8 , since it inherits the virtual base class Derived1, so vptr is added by the compiler ( sizeof(vptr) = 8 on the 64 bit machine), and therefore sizeof(Derived2) shows 8 bytes.

sizeof(Derived3) = 1 due to 1 char byte.

sizeof(Derived4) = 16 , the internal implementation of Virtual inheritance is completely dependent on the compiler, because of this you see 16 bytes as the size.

sizeof(Dummy) = 1 Because it contains a single char object.

+1
source

Empty has a size of 1, because each object must have a size of at least 1.

Derived1 has a size of 1 for the same reason.

Derived2 is 8 because your compiler needs 8 bytes for virtual inheritance (probably a pointer).

Derived3 is 1 because your compiler applied the "empty base class" optimization.

Derived4 is 16 because the 8 bytes needed for virtual inheritance make the object necessary 8-byte alignment.

Dummy has size 1 because it is the size of a char .

+1
source

All Articles