- 2074 Chaitra · 4 marks
Ambiguity and how to resolve it
Short answer
Ambiguity arises when a derived class has the same member name from multiple base classes or multiple copies. Resolution methods: use the scope resolution operator (Base::member), override the member in the derived class, or use virtual base class for diamond problem to have a single copy.
What is ambiguity? How can it be resolved? Explain with a suitable example.
Ambiguity is a situation in which the compiler cannot decide which member to use because the same name is available from more than one place. In inheritance it occurs when:
- Two base classes (multiple inheritance) have a member with the same name, and the derived class uses it.
- A class inherits the same base through two paths (diamond problem), giving two copies of its members.
Example:
#include <iostream>
using namespace std;
class A {
public:
void show() { cout << "Class A" << endl; }
};
class B {
public:
void show() { cout << "Class B" << endl; }
};
class C : public A, public B { };
int main() {
C obj;
// obj.show(); // ERROR: ambiguous - A::show() or B::show()?
obj.A::show(); // resolved with scope resolution operator
obj.B::show();
return 0;
}
Output:
Class A
Class B
Ways to resolve ambiguity
- Scope resolution operator
::- name the class explicitly, as inobj.A::show(). - Override in the derived class - define
show()inC, which then hides both and can callA::show()andB::show()as needed. - Virtual base class - for the diamond problem, declare the common base as
virtualso only one copy exists.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Function overriding and how to resolve it · Object Oriented Programming, chapter 6