Let's take this example
class myClassBase
{
public:
int baseMember;
myClassBase() { baseMember = 0; }
virtual int baseMethod(int x) { return baseMember + x; }
};
class myClassBase2
{
public:
int baseMember2;
myClassBase2() { baseMember2 = 0; }
virtual int baseMethod2(int x) { return baseMember2 + x; }
};
class myClassDerived : public myClassBase, public myClassBase2
{
public:
int derivedMember;
myClassDerived() { derivedMember = 0; }
virtual int derivedMethod(int x) { return derivedMember + x; }
};
To understand this, let's us first think that the myClassDerived inherits only from myClassBase, then its equivalent C structure will be
struct myClassDerived
{
struct myClassBase base;
int derivedMember;
};
- The myClassDerived.base will have a pointer to vtable.
- myClassDerived will override this vtable and will put pointer to its own vtable.
- This vtable will have pointer to all virtual function defined in myClassBase and myClassDerived.
- The typeinfo and vtable structure will be same as described previously.
Now if the myClassDerived inherits from both base classes then equivalent C structure will become
struct myClassDerived
{
struct myClassBase base;
struct myClassBase2 base2;
int derivedMember;
};
- As the myClassBase2 has virtual functions, then myClassDerived.base2 will have a pointer to vtable.
- Now the object of myClassDerived will have two pointers to two different vtable.
- One vtable is used if the virtual functions defined in myClassBase or myClassDerived is called. And the other vtable is used if the virtual function which is defined in myClassBase2 is called.
- The myClassDerived creates its own two vtable overrides that are there in base and base2.
- Casting of object from one type to other will works as described previously where inheritance without virtual function is described.
Here is a diagram describing the relations:
Question: How many vtable pointers will be there with the object of myClassDerived if the myClassBase2 derives from two different classes?