How many vptrs are usually needed for a object whose clas( child ) has single inheritance with a base class which multiple inherits base1 and base2. What is the strategy for
Anything regarding vptr/vtable is not specified, so this is going to be compiler dependent for the fine details, but the simple cases are handled the same by almost every modern compiler (I write "almost" just in case).
You have been warned.
If you inherit from base classes, and they have a vptr, you naturally have as many inherited vptr in your class.
The question is: When will the compiler add a vptr to a class that already has an inherited vptr?
The compiler will try to avoid adding redundant vptr:
struct B {
virtual ~B();
};
struct D : B {
virtual void foo();
};
Here B
has a vptr, so D
does not get its own vptr, it reuses the existing vptr; the vtable of B
is extended with an entry for foo()
. The vtable for D
is "derived" from the vtable for B
, pseudo-code:
struct B_vtable {
typeinfo *info; // for typeid, dynamic_cast
void (*destructor)(B*);
};
struct D_vtable : B_vtable {
void (*foo)(D*);
};
The fine print, again: this is a simplification of a real vtable, to get the idea.
For non virtual single inheritance, there is almost no room for variation between implementations. For virtual inheritance, there are a lot more variations between compilers.
struct B2 : virtual A {
};
There is a conversion from B2*
to A*
, so a B2
object must provide this functionality:
A*
memberoffset_of_A_from_B2
offset_of_A_from_B2
in the vtableIn general, a class will not reuse the vptr of its virtual base class (but it can in a very special case).