#include<iostream> using namespace std; class A { int a; int b; public: void eat() { cout<<'A::eat()'<<endl; } }; class B: public A { public: void eat() { cout<<'B::eat()'<<endl; } }; class C: public A { public: void eat() { cout<<'C::eat()'<<endl; } }; class D: public B, C { }; int foo(A *ptr) { ptr->eat(); } main() { D obj; foo(&(obj.B)); //error. How do i call with D's B part. }
The above foo call is a compile time error. I want to call foo with obj’s B part without using virtual inheritance. How do i do that.
Also, in case of virtual inheritance, why the offset information need to be stored in the vtable. This can be determined at the compile time itself. In the above case, if we pass foo with D’s object, at compile time only we can calculate the offset of D’s A part.
Inheriting twice
With double inheritance you have an ambiguity – the compiler cannot know which of the two A bases do you want to use. If you want to have two A bases (sometimes you may want to do this), you may select between them by casting to B or C. The most appropriate from default casts here is the
static_cast(as the weakest available), however it is not realy needed (it is still stronger than your case needs), as you are not casting to a derived type. A customsafe_casttemplate should do the job:Compile time types – use templates
This is a misconception. The foo function as it is written now has no compile type information about ptr type other than it is A *, even if you pass B * or C*. If you want foo to be able to act based on the type passed compile time, you need to use templates:
Virtual Inheritance
Your questions mentions virtual inheritance. If you want to use virtual inheritance, you need to specify so:
With this the code would compile, but with this solution there is no way you could select between B::A or C::A (there is only one A), therefore this is probably not what you are about.
Virtual functions
Furthermore, your questions seems to be confusing two different concepts, virtual inheritance (which means sharing one base class between two intermediate base classes) and virtual functions (which mean allowing derived class function to be called via base class pointer). If you want the B::eat to be called using A pointer, you can do this without virtual inheritance (actually virtual inheritance would prevent you doing so, as explained above), using virtual functions:
If virtual functions are not acceptable for you, the compile time mechanism for this are templates, as explained above.