#include <iostream>
using namespace std;
class A
{
public:
A(){cout<<"Constructing A \n";}
~A(){cout<<"Destructinf A \n";}
int x;
};
class B : virtual public A
{
public:
B(){cout<<"Constructing B \n";}
~B(){cout<<"Destructinf B \n";}
int x=20;
};
class C : virtual public A
{
public:
C(){cout<<"Constructing C \n";}
~C(){cout<<"Destructinf C \n";}
int x=50;
};
class D : public B,public C
{
public:
D(){cout<<"Constructing D \n";}
~D(){cout<<"Destructinf D \n";}
};
int main()
{
D obj;
obj.x; //x invoked
cout<<obj.x<<"\n";
return 0;
}
Output error: request for member ‘x’ is ambiguous
Although I have used virtual class, still I am getting the above error.Do I have to remove One of the x declared in class B and Class C or is there any way to solve this error
The lookup set for the name
xin the derived classDincludes two names in its direct base classes{ B::x, C::x }. So using the unqualified namexin these statementsis ambiguous.
You could use qualified names like for example
If you will remove the data member x in one of the base classes of the class
Dthen there will be no ambiguity and you may write (for example if to remove the data memberxin the classB)If you want tp have one data member with the name x then remove it from the both classes B and C as for example
Pay attention to that the destructor should be declared as virtual.