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 class of Base
, so it seems natural that line B doesn't compile. But, on the other hand, variable b
has the public member nested
, and I can call its method Do()
from outside of Base
(as in line A). What are the precise rules that regulate access to the private nested class (or its members) in such case? What does the standard say on this?
According to the standard, $11.7/1 Nested classes [class.access.nest]:
So, it's quite simple.
NestedBase
is aprivate
member of classBase
, soBase::NestedBase
can't be accessed inmain()
.b.nested.Do();
is fine becausenested
andDo()
are bothpublic
members. The fact thatNestedBase
is aprivate
nested class ofBase
doesn't matter, it's irrelevant here.