Concept of Ambiguity Resolution in Inheritance of C++

Mannan Ul Haq
0
Ambiguity in inheritance occurs when a derived class inherits multiple functions or data members with the same name and the compiler cannot determine which member to access. C++ provides rules for resolving such ambiguities, and these rules vary depending on the type of ambiguity encountered.

There are two main types of ambiguities in inheritance:

1. Name Ambiguity:

Name ambiguity occurs when a derived class inherits multiple data members with the same name from different base classes. The compiler cannot determine which member to access when using that name. To resolve name ambiguity, you need to qualify the member with the class name or use a using declaration to bring the members into scope.

Example:

class Base1
{
public:
    int value = 5;
};

class Base2
{
public:
    int value = 10;
};

class Derived : public Base1, public Base2
{
public:
    void displayValues()
    {
        cout << "Base1 value: " << Base1::value << endl;
        cout << "Base2 value: " << Base2::value << endl;
    }
};

int main()
{
    Derived derivedObj;
    derivedObj.displayValues();
    return 0;
}

 

Output:

Base1 value: 5
Base2 value: 10

In this example, the `Derived` class inherits `value` from both `Base1` and `Base2`. To access the correct `value` member, we use the scope resolution operator (`::`) and specify the class name before the member name.

2. Function Ambiguity:

Function ambiguity occurs when a derived class inherits multiple functions with the same name and signature from different base classes. The compiler cannot determine which function to invoke. To resolve function ambiguity, you can explicitly specify the desired function using the scope resolution operator or provide a new function in the derived class that overrides the base class functions.

Example:

class Base1
{
public:
    void display()
    {
        cout << "Base1 display()" << endl;
    }
};

class Base2
{
public:
    void display()
    {
        cout << "Base2 display()" << endl;
    }
};

class Derived : public Base1, public Base2
{
public:
    void display()
    {
        cout << "Derived display()" << endl;
    }
};

int main()
{
    Derived derivedObj;
    derivedObj.display();  // Output: Derived display()
    derivedObj.Base1::display();  // Output: Base1 display()
    derivedObj.Base2::display();  // Output: Base2 display()
    return 0;
}

In this example, the `Derived` class inherits the `display()` function from both `Base1` and `Base2`. To resolve function ambiguity, we can override the function in the derived class with its own implementation. Alternatively, we can use the scope resolution operator to explicitly specify the base class whose function we want to invoke.

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !