Reputation: 1309
I got an error ambiguous access mg
. but mg is only protected and inherited using public access. why is it so? throw some light please. Thanks for your time !
class A{
protected:
int mg;
static int ms;
};
class B : public A{
protected:
using A::ms;
};
class C : public A, public B{
public:
void fn(){
cout << mg;
cout << ms;
}
};
int A::ms = 0;
int main(){
C c;
c .fn();
}
Upvotes: 1
Views: 1835
Reputation: 9388
in C
, A::mg
can refer to the one inherited from A
, or to the one inherited from B
because B
inherits A
. So the call is ambiguous : which one do you really refer to ?
Using virtual inheritance can solve this problem. You can see this answer which is on a problem really similar than yours : the diamond inheritance.
Upvotes: 2
Reputation: 42649
In this example, you have two copies of the base class A
in class C
, as B
already derives from A
. This also gives a base class of A
in C
:
class C : public B{
public:
void fn(){
cout << mg;
cout << ms;
}
};
This problem is known as the "diamond of death" and is used to explain the danger of multiple inheritance. Except here it has been reduced to a "triangle of death."
Upvotes: 2