- 2068 Baisakh · 2+6 marks
Ambiguity in multiple inheritance
Short answer
Ambiguity arises when two base classes have identically named members; the compiler cannot resolve which to use. Example: Child inherits Father and Mother, both with show(). Calling c.show() is ambiguous; use c.Father::show() to resolve.
Explain the case of ambiguity in inheritance. Write a program that shows ambiguity in multiple inheritance.
Ambiguity in inheritance
Ambiguity arises when the compiler finds more than one possible meaning for a name and cannot choose. In multiple inheritance, if two base classes have a member (data or function) with the same name and the derived class does not define its own, a call such as obj.show() is ambiguous. A second case is the diamond problem, where the final class has two copies of a common grandparent.
It is resolved with the scope resolution operator (obj.A::show()), by redefining the member in the derived class, or by using a virtual base class for the diamond case.
Program showing ambiguity
#include <iostream>
using namespace std;
class Father {
public:
void show() { cout << "Father's show()" << endl; }
};
class Mother {
public:
void show() { cout << "Mother's show()" << endl; }
};
class Child : public Father, public Mother {
};
int main() {
Child c;
// c.show(); // ERROR: reference to 'show' is ambiguous
c.Father::show(); // resolved using scope resolution operator
c.Mother::show();
return 0;
}
If the commented line c.show(); is enabled, the compiler gives an error like request for member 'show' is ambiguous, since both Father::show() and Mother::show() are equally valid.
Output (after resolution):
Father's show()
Mother's show()
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Constructor and destructor order, multilevel inheritance · Object Oriented Programming, chapter 6 · asked 2×
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6
- Correct program: case array and average · Computer Programming, chapter 3
- Bidding preparation, ambiguity, percentage contract · Engineering Professional Practice, chapter 4
- Convert case based on first character · Computer Programming, chapter 7