virtual inheritance and sizes

I know why the size of Derived1 is 1
but why the size of Derived3 is 8
what does virtual keyword do in this place regardless of preventing double inheritance ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

class Empty
{};

class Derived1 : public Empty
{};

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

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

	return 0;
}
Last edited on
I am assuming you are compiling this as a 32-bit program such that your pointer sizes are usually 4 (i.e. 32-bit addresses).

The reason it is 8 is because 1 byte is for the char, and 4 bytes is for the address of the shared base class object. This is 5 bytes in total, but due to padding/aliasing rules, the compiler rounds up to 8, with 3 bytes of padding.

The way that it handles "double inheritance" (a.k.a. multiple inheritance, or the "diamond problem") is by having both subclass objects point to the same base class object.
Last edited on
Thank you
Topic archived. No new replies allowed.