I was going through this:- https://isocpp.org/wiki/faq/multiple-inheritance#mi-delegate-to-sister
Can Someone give me an explaination of how does this happens and why does this happens?
I was going through this:- https://isocpp.org/wiki/faq/multiple-inheritance#mi-delegate-to-sister
Can Someone give me an explaination of how does this happens and why does this happens?
The key, missing from two of the other answers is that there is virtual inheritance in place. This means that in the complete object there is only one Base
subobject, which is shared by Der1
and Der2
.
Each one of the Der1
and Der2
types provides the implementation of one of the virtual functions of that base, and since there is only one such object, the combination of Der1
and Der2
provide the implementation of both members inside the complete object.
You can dispatch to the sibling class as you are really calling a member function of your Base
type, and that function is implemented in your Base
subobject (by means of your sibling class). Note that Der1
does not call Der2::bar
, but rather Base::bar
which is then dispatched to the final overrider that happens to be in Der2
. This is really not different from dispatch to the final overrider in other cases:
struct base { virtual void f() = 0; };
struct d : base { void g() { f(); } };
struct d1 : d { void f() { std::cout << "here"; };
int main() {
d1 x;
x.g(); // dispatches from 'd::g' to 'd1::f' which is below in the hierarchy!
// yeah, right, everyone knows that... no magic here
}
Now if inheritance wasn't virtual, there would be two Base
subobjects in the complete type, each one of which would have a (different) pure virtual function and you would not even be able to instantiate an object of the most derived type (unless that provided the definitions for the virtual functions)
Because this are the virtual functions and call is call to function from VirtualFunction table. It's just a lookup in table by defined index. This table get it data when object is constructed, and since dynamic type of the object is Join, and this type have entries for all virtual functions, inherited from base classes.
Short answer would be:
Although the Join class is derived from Der1 and Der2, there will be only one instance of Base class. That's because of virtual inheritance. If Base class wouldn't be abstract class and if you would have to pass some arguments to the constructor, these call would be omitted in both, Der1 and Der2 and you would have to pass these arguments through the Join.
© 2022 - 2024 — McMap. All rights reserved.