Reputation: 207
class A
{
protected:
string word;
};
class B
{
protected:
string word;
};
class Derived: public A, public B
{
};
How would the accessibility of the variable word
be affected in Derived
? How would I resolve it?
Upvotes: 20
Views: 7856
Reputation: 409166
You can use the using
keyword to tell the compiler which version to use:
class Derived : public A, public B
{
protected:
using A::word;
};
This tells the compiler that the Derived
class has a protected member word
, which will be an alias to A::word
. Then whenever you use the unqualified identifier word
in the Derived
class, it will mean A::word
. If you want to use B::word
you have to fully qualify the scope.
Upvotes: 26
Reputation: 781
Your class Derived
will have two variables, B::word
and A::word
Outside of Derived
you can access them like this (if you change their access to public):
Derived c;
c.A::word = "hi";
c.B::word = "happy";
Attempting to access c.word
will lead to an error, since there is no field with the name word
, but only A::word and B::word.
Inside Derived
they behave like regular fields, again, with the names A::var
and B::var
also mentioned in other answers.
Upvotes: 6
Reputation: 49251
It will be ambiguous, and you'll get a compilation error saying that.
You'll need to use the right scope to use it:
class Derived: public A, public B
{
Derived()
{
A::word = "A!";
B::word = "B!!";
}
};
Upvotes: 36
Reputation: 6555
When accessing word
in the class of Derived
, you had to declare
class Derived: public A, public B
{
Derived()
{
A::word = X;
//or
B::word = x;
}
};
Upvotes: 3