How many vtable pointers in one derived object in single virtual inheritance?

How many vtable pointers in b1 (Visual studio 2010)?
The answer is 2 if CMultiBase1 add virtual functions or 1 if CMultiBase1 add no virtual functions.

struct CMultiBase
	int mbase;
	virtual int f()
		return EBASE1;
struct CMultiBase1: virtual CMultiBase
	int f()
		return EBASE2;
	virtual int f1()
		return EBASE3;
void TestVirtualSingleInheritance()
	CMultiBase1 b1; //we have only one object
	CMultiBase *pb = &b1;
	CMultiBase1 *pb1 = &b1;
	unsigned int * pRawDword = reinterpret_cast(&b1); //points to the first DWORD of our project
	_ASSERT(sizeof(unsigned int) == 4);
	std::cout << std::hex << pb << " " << pb1;
	_ASSERT(reinterpret_cast(pb) != reinterpret_cast(pb1));

(pRawDword + 0) points to the newly added part of CMultiBase1’s vtable,
because *(int*)(*(pRawDword +0)) shows CMultiBase1::f1().
(pRawDword + 2) points to the part of CMultiBase1’s vtable that was originally from CMultiBase,
because *(int*)(*(pRawDword +2)) shows CMultiBase ::f ()
Therefore, there are two vtable pointers in b1, pRawDword+2 and pRawDword+0
Here is how to see virtual function addresses:
From the watch window in Visual Studio, expand pb, expand __vfptr.
It can also be seen that if CMultiBase1 doesn’t introduce any new virtual functions(take out f1), there is only one vtable pointer, and (pRawDword + 0) instead points to vbptr(virtual base table pointer).

Comments are closed.
%d bloggers like this: