Multiple inheritance and virtual functions

Started by
2 comments, last by SiCrane 18 years, 9 months ago
I've been researching for a few days to figure out how C++ compilers handle mutliple inheritance of base classes with virtual functions in them. It seems to me that the only way that this could work would be either by the compiler outputting code to do the typeid of the class on any call or some similar hack, does anyone know how this is handled / have any links about it? Thanks, ~SPH
AIM ME: aGaBoOgAmOnGeR
Advertisement
With multiple inheritance and virtual functions, the derived class will contain multiple vptrs. In essence a derived class contains each of its base classes as subobjects, which in turn have different addresses within the derived class. So when used as one base class it has a different address than when used as a different base class. Code that uses the derived class as a base class just references the base class vtable as normal. To handle differences in the address of the base subobject vs. the natural address of the derived class, the vtable in addition to the pointer to member function also will contain a pointer offset, or a jump to a thunk that fixes up the this pointer when accessing the virtual function.

For more information you can read Design and Evolution of C++ by Bjarne Strostrup or the C++ Object Model by Stanley Lippman.
Are you saying that when converting from a pointer to the derived class to a pointer to the base class C++ simply offsets the address by an appropriate amount? (And the other way around too I would imagine)

That's a clever way to do it... still mulling over the possible problems though.

Thanks, ~SPH
AIM ME: aGaBoOgAmOnGeR
It may or may not need to change a pointer to a derived class when converting to a base class. In general, compilers generally have one base subobject be at the same address as the natural address of the derived class. When converting pointers between these two types no change in address needs to be done. However conversion between pointers of other base classes will need to have a pointer update done. This is one reason why reinterpret_casts can be so dangerous, since a reinterpret_cast may cause a valid pointer to a derived class to be converted to a invalid pointer to a base class even if a static_cast would have done the right thing.

This topic is closed to new replies.

Advertisement