Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested classes: Access to protected member of enclosing class from a nested protected class

Tags:

c++

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.

like image 751
SigTerm Avatar asked Aug 21 '10 14:08

SigTerm


People also ask

Can protected members are accessible to the member of derived 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.

Can nested classes access private members?

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.

Which methods can access the protected members of a class?

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.

Can nested classes access private members in Java?

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.


1 Answers

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.

like image 55
Håvard S Avatar answered Nov 01 '22 09:11

Håvard S