I have a Class B, which is inheriting Class A. I have a Class C, which is inheriting Class B and Class A;
There is a variable named "a" in class A which I have to access in class D, but not by using resolution operator on class B for example , d.B::a;
#include<bits/stdc .h>
using namespace std;
class A{
public:
int a;
};
class B : public A{
public:
int b;
};
class D : public B, public A{
public:
int d;
};
int main() {
D d;
d.B::a = 1; // This is working correctly on this path class D -\> class B -\> class A
d.a = 2;
/*
But This line gives the following error
Non-static member 'a' found in multiple base-class subobjects of type 'A':
class D -> class B -> class A
class D -> class A
*/
return 0;
}
int main() {
D d;
d.D::a = 2; //This is not working correctly on this path class D -\> class A
d.A::a = 2; //This is not working correctly on this path class D -\> class A
//How do I use Scope Resolution to access variable "a" from second path ?!
return 0;
}
CodePudding user response:
B already inherits from A, so D should only inherit from B:
class A{
public:
int a;
};
class B : public A{
public:
int b;
};
class D : public B{
public:
int d;
};
If you had another class C that also inherits from A, and you would want D to inherit from B and C, then you would have the diamond problem. Then, to avoid ambiguity, you should write:
class A{
public:
int a;
};
class B : virtual public A{
public:
int b;
};
class C : virtual public A{
public:
int b;
};
class D : public B, public C{
public:
int d;
};
CodePudding user response:
Virtual inheritance is key words for your problem.
Try this one :
#include<bits/stdc .h>
using namespace std;
class A{
public:
int a;
};
class B : virtual public A{
public:
int b;
};
class D : public B, virtual public A{
public:
int d;
};
int main() {
D d;
d.B::a = 1; // This is working correctly on this path class D -\> class B -\> class A
d.a = 2;
std::cout << d.a;
/*
But This line gives the following error
Non-static member 'a' found in multiple base-class subobjects of type 'A':
class D -> class B -> class A
class D -> class A
*/
return 0;
}