Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 377
tower120 Avatar asked Oct 23 '25 00:10

tower120


1 Answers

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
}
like image 102
WhiZTiM Avatar answered Oct 24 '25 15:10

WhiZTiM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!