Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private base class accessibility in C++

Tags:

c++

I recently had to do something like this:

class A { };
class B : private A { };
class C : public B {
    public:
        A *myA;
};

int main() {
    return 0;
}

And I get an error in the three compilers I tried. When I changed the declaration of myA to ::A *myA everything works ok. I poked around in the C++ standard and found Section 11.2, paragraph 3 where it says:

Note: A member of a private base class might be inaccessible as an inherited member name, but accessible directly.

Which is relevant, but unclear. Why is the name A inaccessible? What problems would occur if A was not hidden?

Thanks,
-Ben

like image 495
Ben Avatar asked Oct 22 '22 08:10

Ben


1 Answers

Where it could "go wrong":

namespace nmsp
{
    class A {};
}

class A {};

class B : private nmsp::A
{
    // well-formed:
    A* d; // refers to the injected-class-name nmsp::A!!
};

class C : public B
{
    // ill-formed
    A* p; // refers to the injected-class-name nmsp::A!!
};

It should not depend on the access-specifier in the base-clause whether ::A or nmsp::A is used, otherwise it'd be error-prone IMO.

like image 107
dyp Avatar answered Nov 03 '22 05:11

dyp