1
#include<iostream>
using namespace std;

class base1{
public:
    int x;
};
class base2{
public:
    int x;
};

class derived1: public base1, public base2{
    // Contains...  base1::x, base2::x
};
class derived2: public base1, public base2{
    // Contains...  base1::x, base2::x 
};

class derived: public derived1, public derived2{

};

If I am right, the class derived will contain four integers. But I can't access them with
derived1::base1::x, derived1::base2::x, derived2::base1::x, derived2::base2::x


It shows ambiguity error. ('base1' is ambiguous base of 'derived')
Am I missing something? How should I resolve this?

1

1 Answer 1

2

Well, when you use the scope resolution operator to disambiguate between members, you don't name a "path" to the member. You instead name, however indirectly, the base class where the member comes from.

Since the class name is injected into the scope of the class, and as a result, into the scope of any class that derives from it, you are just naming base1 and base2 in a verbose manner. I.e. all the following are equivalent for the member access:

derived d;
d.base1::x;
d.derived1::base1::x;
d.derived1::derived1::base1::base1::x;

That's why the ambiguity occurs. The way to do it, is to cast the object into a derived1& or derived2&, and then use member access via base1::x and base2::x on that.

static_cast<derived1&>(d).base1::x;
Sign up to request clarification or add additional context in comments.

4 Comments

Good technique! The one (and only) time I got to speak with Bjarne, I had asked him how one should do that. Now I know.
Didn't know that. Thank you very much.
what if x is declared protected: in base1 and base2?
@SymonSaroar - Access specifiers don't affect how lookup works. They only make the access allowed or disallowed after the lookup is done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.