C ++: public member of a private type of a nested class

I have the following code:

class Base { private: class NestedBase { public: void Do() {} }; public: NestedBase nested; }; int main() { Base b; b.nested.Do(); // line A compiles Base::NestedBase instance; // line B doesn't compile } 

NestedBase class is a private nested Base class, so it seems natural that line B does not compile. But on the other hand, the variable b has the public member nested , and I can call its Do() method from outside Base (as in line A). What are the exact rules governing access to a private nested class (or its members) in this case? What does the standard say about this?

+8
c ++ inner-classes class-visibility
source share
2 answers

According to the standard $ 11.7 / 1 Nested classes [class.access.nest] :

A nested class is a member and, as such, has the same access rights as any other member.

So this is pretty simple. NestedBase is a member of the private Base class, so Base::NestedBase not available in main() .

b.nested.Do(); excellent because nested and Do() are members of public . The fact that NestedBase is a private nested Base class does not matter; here it does not matter.

+6
source share

The type name NestedBase is a private member of the class.

 class Base { private: class NestedBase { public: void Do() {} }; //... 

Thus, you cannot explicitly access it outside the class in which the name is declared.

But you can access the name implicitly as follows :)

 decltype( Base::nested) instance; 
+2
source share

All Articles