Search code examples
c++multiple-inheritanceaccess-controlprivate-membersname-lookup

C++ multiple inheritance private member ambigious access


The following code:

class A1 {
public:
    int x;
};
class A2 {
private:
    int x() { return 67; }
};

class M : public A1, public A2 {};

int main() {
    M m;
    m.x;
}

Compiles with error:

error C2385: ambiguous access of 'x'
note: could be the 'x' in base 'A1'
note: or could be the 'x' in base 'A2'

But why? only A1::x should be visible to M. A2::x should be purely local.


Solution

  • In C++, name-lookup happens before member access checking is performed. Hence, name-lookup (Unqualified in your case) finds two names, and that's ambiguous.

    You can use a qualified name to disambiguate:

    int main() {
        M m;
        m.A1::x;     //qualifed name-lookup
    }