Nested classes have access to private members

Consider the following code:

class A{
public:
    class B{
    public:
    void useA(A * pA){
       pA->m_int = 23;
    }
};
private:
    int m_int;
};
int main(){
    A a;
    A::B b;
    b.useA(&a);
    return 0;
}

Compiles well on all compilers which I have: gcc 3.2.3, VC 7.1, Comeau 4.3.9.
The point is that C++ standard was not always consistent about the access mode of a nested class.
So some compilers built before 1995 (or even 1999) can actually refuse this code.
Currently (ISO 2003), the following rules apply:
A nested class is implicitly a friend of each enclosing class.
The members of an enclosing class, on the other hand, have no special access to members of a nested class; the usual access rules shall be obeyed.

One can check original proposition paper.

Leave a Reply