Q. Describe ambiguity in multiple inheritance. How can it be resolved?
In multiple inheritance, there may be a possibility that a class may inherit
member functions with the same name from two or more base classes and the
derived class may not have function with the same name. If the object of the
derived class need to access one of the member functions with the same name
which are derived from base classes then it results in ambiguity. The compiler
doesn’t know which function from different base classes to execute.
To understand the problem, consider the following program.
//Program to demonstrate ambiguity in multiple inheritance
#include<iostream.h>
class base1
{
protected:
int n1;
public:
void read()
{
cout<<endl<<"Enter Number1";
cin>>n1;
}
void show()
{
cout<<endl<<"Number1="<<n1;
}
}; //Declaration of base1 completed
class base2
{
protected:
int n2;
public:
void read()
{
cout<<endl<<"Enter Number2";
cin>>n2;
}
void show()
{
cout<<endl<<"Number2="<<n2;
}
}; //Declaration of base2 completed
//class derived, multiply derived from base1 & base2
class derived : public base1,public base2
{
private:
int s;
public:
void sum()
{
s=n1+n2;
cout<<endl<<"Sum="<<s;
}
};
int main()
{
derived d;
d.read(); //ambiguous call to function read()
d.read(); //ambiguous call to function read()
d.sum();
return(0);
}
In the above written program, both classes base1 & base2 have the function
read(). The derived class ‘derived’ doesn’t have a function with the same name
read(). On executing d.read(), the compiler generates an error message that the
function call to read() is ambiguous as it is not clear to the compiler that which
version of read() is to be called whether read() of base1 or base2.
Base1 Base2
Protected: Protected:
................... .................
Public: Public:
Void Read() Void Read()
derived
Private:
........................
Public:
void sum();
void read();
void read();
Fig a: Ambiguity in multiple inheritance
Resolution:
The ambiguity can be resolved by using the scope resolution operator (::) to
specify the class to which the member function belongs to as given below:
d.base1::read();
This statement on execution will invoke read() member function of the class
base1. Similarly the statement
d.base2::read();
invokes read() member function of base2.
The above written program can be rewritten as follows:
//Program to demonstrate ambiguity in multiple inheritance
#include<iostream.h>
class base1
{
protected:
int n1;
public:
void read()
{
cout<<endl<<"Enter Number1";
cin>>n1;
}
void show()
{
cout<<endl<<"Number1="<<n1;
}
};
class base2
{
protected:
int n2;
public:
void read()
{
cout<<endl<<"Enter Number2";
cin>>n2;
}
void show()
{
cout<<endl<<"Number2="<<n2;
}
};
class derived : public base1,public base2
{
private:
int s;
public:
void sum()
{
s=n1+n2;
cout<<endl<<"Sum="<<s;
}
};
void main()
{
derived d;
d.base1::read(); //call to function read() of base1
d.base2::read(); //call to function read() of base2
d.sum();