c++inner-classesfriend

Are inner classes in C++ automatically friends?


If I define an inner class in C++, is it automatically a friend of the class that contains it? For example, is this legal?

class Outer {
public:
    class Inner {
    public:
        void mutateOuter(Outer& o);
    };

private:
    int value;
};

void Outer::Inner::mutateOuter(Outer& o) {
    o.value ++; // Legal?  Or not?
}

I ask because on some compilers I've tried (VS2003) this code won't work, but I've heard at least anecdotally that it does work on some compilers. I can't find a relevant section in the C++ spec about this, and if anyone can cite something specific that would say that it is or is not legal that would be great.


Solution

  • After having asked more or less the same question here myself, I wanted to share the (apparently) updated answer for C++11:

    Quoted from https://stackoverflow.com/a/14759027/1984137:

    standard $11.7.1

    "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 shall be obeyed"

    and the usual access rules specify that:

    "A member of a class can also access all the names to which the class has access..."

    specific examples has been given in the standard:

    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
            }
        };
    }