C++ Ambiguity in multiple inheritance

In multiple inheritance, there may be possibility that a class may inherit member functions with same name from two or more base classes and the derived class may not have functions with same name as those of its base classes. If the object of the derived class need to access one of the same named member function of the base classes then it result in ambiguity as it is not clear to the compiler which base’s class member function should be invoked. The ambiguity simply means the state when the compiler confused.

 

Syntax:

class a

{

private:

…………….

public:

void abc() {}

…………….

…………….

};

class b

{

private:

…………….

public:

void abc() {}

…………….

…………….

};

class c : public a , public b

{

private:

…………….

public:

…………….

…………….

};

void main()

{

c obj;

obj.abc();//Error

……………..

}

 

In this example, the two base classes a and b have function of same name abc() which are inherited to the derived class c. When the object of the class c is created and call the function abc() then the compiler is confused which base’s class function is called by the compiler.

 

Solution of ambiguity in multiple inheritance: The ambiguity can be resolved by using the scope resolution operator to specify the class in which the member function lies as given below:

obj.a :: abc();

 

This statement invoke the function name abc() which are lies in base class a.

Leave a Reply

Your email address will not be published. Required fields are marked *