Skip to main content

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:

  1. Two base classes (multiple inheritance) have a member with the same name, and the derived class uses it.
  2. 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

  1. Scope resolution operator :: - name the class explicitly, as in obj.A::show().
  2. Override in the derived class - define show() in C, which then hides both and can call A::show() and B::show() as needed.
  3. Virtual base class - for the diamond problem, declare the common base as virtual so only one copy exists.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 6 questions →