What does virtual inheritance mean?

It’s well known that virtual inheritance is to solve the diamond problem.
Here I dig a little deeper, with only two classes.
struct B: virtual A {…}; What difference is ‘virtual’ making here?

struct CMultiBase
	int mbase;
struct CMultiBase1: virtual CMultiBase
	int mbase1;
void TestVirtualSingleInheritance()
	CMultiBase1 b1;
	CMultiBase *pb = &b1;
	CMultiBase1 *pb1 = &b1;
	std::cout << std::hex << pb1 << " " << &pb->mbase;
	_ASSERT(reinterpret_cast<void**>(pb1) + 2 == reinterpret_cast<void*>(&pb->mbase));
	// this assertion fails if no 'virtual'. Adding 2 to skip vbptr and mbase1

Without ‘virtual’, mbase is the the first member in CMultiBase1, and therefore pb1 == &pb->mbase, and the _ASSERT fails.
With ‘virtual’, vbptr, instead of mbase, becomes the first member in CMultiBase1, and therefore the _ASSERT succeeds.
To put it simply, ‘virtual’ moves the base class away from the beginning of the derived class, and vbptr tells where the base class goes.

Comments are closed.
%d bloggers like this: