This code compiles on msvc/g++:
class A{
protected:
int i;
class B{
public:
A* a;
B(A* a_)
:a(a_){
}
void doSomething(){
if (a)
a->i = 0;//<---- this part
}
};
public:
A()
:i(0){
}
};
As you can see, B gets access to "protected" section of enclosing class, although it isn't declared as friend.
Is this a standard(standard-conforming) behavior?
I use this feature sometimes, but I don't remember a rule saying that nested protected class should automatically get access to all protected data of enclosing class.
Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.
Protected members in a class are similar to private members as they cannot be accessed from outside the class. But they can be accessed by derived classes or child classes while private members cannot.
Not only does the nested class have access to the private fields of the outer class, but the same fields can be accessed by any other class within the package when the nested class is declared public or if it contains public methods or constructors.
In the C++03 standard, 11.8p1 says:
The members of a nested class have no special access to members of an enclosing class.
However, the resolution for defect report 45 (to the standard) states the opposite, and hence defines the behavior you see:
A nested class is a member and as such has the same access rights as any other member.
In C++0x the text of 11.8 has been changed to reflect this fact, so this is valid behavior for both C++03 and C++0x conforming compilers.
See also this thread from the cprogramming.com forums.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With