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

899 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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, it's quite simple. NestedBase is a private member of class Base, so Base::NestedBase can't be accessed in main().

b.nested.Do(); is fine because nested and Do() are both public members. The fact that NestedBase is a private nested class of Base doesn't matter, it's irrelevant here.

1
On

Type name NestedBase is a private member of the class.

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

So you can not explicitly access it outside the class where the name is declared.

But you can access the name implicitly the following way:)

decltype( Base::nested) instance;