4

As described in ISO C++ 2003

§11.8 Nested classes [class.access.nest]

The members of a nested class have no special access to members of an enclosing class, nor to classes or functions that have granted friendship to an enclosing class; the usual access rules (clause 11) shall be obeyed. The members of an enclosing class have no special access to members of a nested class; the usual access rules (clause 11) shall be obeyed.

[Example:

class E {
    int x;

    class B { };

    class I {
        B b; // error: E::B is private ERROR 1
        int y;
        void f(E* p, int i)
        {
            p->x = i; // error: E::x is private ERROR 2
        }
    };

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

int main()
{}

—end example]

So I think that clang and g++ are wrong as they compile this code successfully.

Or do I understand something wrong?

dyp
  • 38,334
  • 13
  • 112
  • 177
  • Related to [CWG DR #45](http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#45) – dyp May 02 '15 at 21:24
  • Related/duplicate of [nested class access control in C++](http://stackoverflow.com/q/3173520/) – dyp May 02 '15 at 21:26

2 Answers2

0

Standard says about "have no special access", but not about "have no access at all". Nested class is a same member of outer class as any other member.

It is not clearly said in C++03 standard, but C++11 contains it explicitly:

11.7 Nested classes [class.access.nest]

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

vladon
  • 8,158
  • 2
  • 47
  • 91
0

This behaviour has changed since 2003. The relevant clause in Working Draft N4926 (C++17) now reads:

§11.7 Nested classes [class.access.nest]

A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules (Clause 11) shall be obeyed.

So the access is one way: nested class members can access enclosing class members, but not vice versa.

For instance:

class Enclosing
{
  int n;
  class Nested
  {
    int n;
    int f (Enclosing& E)
    {
      return E.n; // OK
    }
  } ;
  int f (Nested& N)
  {
    return N.n; // Error: Nested::n is private
  }
} ;
Community
  • 1
  • 1
TonyK
  • 16,761
  • 4
  • 37
  • 72
  • AND vice versa, they are equal in access rights to each other. – vladon Oct 01 '15 at 12:42
  • @VladislavYaroslavlev: Not in C++17 they don't. – TonyK Oct 01 '15 at 14:56
  • what exactly forbids the access? The rule says: "no special access", not "no access". Any private member can see any other private member. That clause (11.7) is in C++11 already, not in C++17. – vladon Oct 01 '15 at 15:30
  • @VladislavYaroslavlev: What forbids it is the phrase "the usual access rules shall be obeyed." I have added an example to my answer. Try it with C++14 or C++17 enabled. – TonyK Oct 01 '15 at 15:39