Reputation:
So here I got a descent explanation that what actually is a virtual function and why do we really need it,
But there still remains a question in my mind that how compiler actually interpret that which definition should be used in case of multiple or hybrid inheritance. For example consider this example
class Up {
public:
void func(){
...
}
};
class Middle_1 : public virtual Up {
public:
...
};
class Middle_2 : public virtual Up {
public:
...
};
class Down : public Middle_1, public Middle_2 {
public:
...
};
In above example code, class Down
is receiving two definition of class Up
(i.e one from Middle_1
and another from Middle_2
). However we had ensured to use the virtual
tag in Middle_1
and Middle_2
class which will remove the case of ambiguity (because compiler will take only one definition) and that is where my question arises.
Actually I am having a bunch of questions,
How will compiler select the best suited class?
Will the selection be similar in all conditions?
Didn't it contradict the fact that compiler have zero IQ?
Thanks in advance.
Upvotes: 0
Views: 814
Reputation: 119847
There's only one Up
class in the entire program. No need to select anything.
Perhaps you wanted to ask how will compiler select the best suited Up
subobject? Ostensibly there's an Up
subobject in each Middle_1
object, and an Up
subobject in each Middle_2
subobject. The compiler will need to select one of them to use with Down
, right?
Wrong. With virtual inheritance, subobjects are not fixed in place relatively to their owners. Neither Middle_1
nor Middle_2
create their own Up
subobjects, and they do not know in advance where these Up
subobjects live. They only know they are going to have one. Somebody will have to hand them down an instance of Up
.
So the compiler will do a little dirty trick. It will create a single Up
subobject for each Down
object, and then tell the Middle_1
part and the Middle_2
part and the Down
part that it is their Up
subobject. So all three parts will treat that single Up
as their own, completely oblivious to the fact that it is in fact shared.
This scheme did require some non-trivial IQ to invent, but every dumb compiler out there is capable of implementing it.
Upvotes: 4