C++ Outer class access Inner class's private - why forbidden

Essentially, within a scope names declared earlier in that scope are valid and can be used directly (unless they're shadowed). Code outside a scope can't directly use names declared inside the scope. E.g. code after a curly braces block, can't directly use variables declared inside that block (an example of indirect use is when the outside code has access to a pointer to a static variable inside the curly braces block).


For the second example, just make Algorithm a friend of AlgorithmResults:

class AlgorithmResults
{
    friend class Algorithm;

The nested classes could access outer class's private fields, because it's a member of the outer class, just same as the other members.

[class.access.nest]/1

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

On the other hand, the outer class doesn't have special access rights on the nested class, they're just normal relationship.

The members of an enclosing class have no special access to members of a nested class; the usual access rules ([class.access]) shall be obeyed. [ Example:

class E {
  int x;
  class B { };

  class I {
    B b;                        // OK: E​::​I can access E​::​B
    int y;
    void f(E* p, int i) {
      p->x = i;                 // OK: E​::​I can access E​::​x
    }
  };

  int g(I* p) {
    return p->y;                // error: I​::​y is private
  }
};

— end example ]


Counter question: Why would you want to allow it?

If you need an outer class have access to an inner class' private internals, you can befriend:

    class Foo {
    public:
            class Frob {
                    friend class Foo;
                    int privateDataMember;
            };

            Foo () {
                    Frob frob;
                    frob.privateDataMember = 3735928559;
            }
    };

C++ has no device to unfriend, so allowing default private access to an outer class would steal you a class design tool and yield reduced default encapsulation.

Tags:

C++

Private