Ambiguity in Multiple Inheritance in C++ is the most common problems occur when we override the functions and we inherit the classes with multiple inheritance.
For example, if we suppose that two-parent classes have the same function which is not overridden in child class.
If you try to call the function using the object of the child class, then the compiler shows error. This problem occurs due to a reason that compiler doesn’t know anything that which function to be called. For example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class Parent1 { public: void YourFunction( ) { .... ... .... } }; class Parent2 { void
YourFunction( ) { .... ... .... } }; class child
: public Parent1, public Parent2 { }; int main() { child object; object.YourFunction() // Error! } |
The solution to the problem of Ambiguity in Multiple Inheritance
The best solution is to use the scope resolution operator with the function to specify that which function of which class is being called.
For example, parent1
or parent2
.
1 2 3 4 5 |
int main() { obj.parent1::yourFunction( ); // Function of parent1 class is called obj.parent2::yourFunction(); // Function of parent2 class is called. } |