Please have a look at the code:
#include <iostream>
using namespace std;
class base1
{
public:
int x,y;
};
class base2
{
public:
int x, z;
};
class derived: virtual public base1,virtual public base2
{
public:
void display(int a, int b, int c)
{
x=a;
y=b;
z=c;
cout<<x<<endl<<y<<endl<<z<,endl;
}
};
int main()
{
derived dr;
dr.display(1,2,3);
}
As the base classes base1 and base2 are made virtual, it should solve the issue of declaration of x in these classes. But, it is not. It is giving me an error: error: reference to ‘x’ is ambiguous Can anyone please put light?
This is not a diamond inheritance issue. You have:
base1 base2
^ ^
| |
\ /
\ /
\ /
\/
derived
The problem is that both base1
and base2
have member x
.
You need to disambiguate x
from derived
using base1::
or base2::
even though you don't have a diamond inheritance.
Ignoring for the time being the rationale for changing the values of member variables in derived::display
, you can use:
class derived: virtual public base1,virtual public base2
{
public:
void display(int a, int b, int c)
{
base1::x=a;
y=b;
z=c;
cout<<base1::x<<endl<<y<<endl<<z<<endl;
}
};