Is there any way to make this C++ program error free or I have to remove one of x declared in one the inherited class

76 Views Asked by At
#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

1

There are 1 best solutions below

1
Vlad from Moscow On

The lookup set for the name x in the derived class D includes two names in its direct base classes { B::x, C::x }. So using the unqualified name x in these statements

obj.x; //x invoked
cout<<obj.x<<"\n";

is ambiguous.

You could use qualified names like for example

D obj;
cout<<obj.B::x<<"\n";
cout<<obj.C::x<<"\n";

If you will remove the data member x in one of the base classes of the class D then there will be no ambiguity and you may write (for example if to remove the data member x in the class B)

D obj;
cout<<obj.x<<"\n";
cout<<obj.C::x<<"\n";

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

class B : virtual public A
{
    public:
    B() { x = 20; cout<<"Constructing B \n";}
    ~B(){cout<<"Destructinf B \n";}
};

class C : virtual public A
{
    public:
    C(){ x = 50; cout<<"Constructing C \n";}
    ~C(){cout<<"Destructinf C \n";}
}

Pay attention to that the destructor should be declared as virtual.