Search code examples
c++classnestedprotected

Access Protected Members of a enclosing class [Nested Classes]


I got the following code:

class enclosing{
protected:
    int var1 = 2;
    int var2 = 4;
public:
    class problem{
    friend enclosing;
    public:
        void DoStuff(enclosing&e1){
            int Sum = e1.var1 + e1.var2;
        }
    }i1;
}e1;

My question is, how do i access the protected member variables of the enclosing class? Is this even Legal?


Solution

  • You have your friendship backwards - a class can't declare itself to be friend of somebody else.

    Unlike in Java's "inner classes", a class defined within a class does not automatically have access to an instance of the class the defines it - the "inner" class is completely independent, and you need to pass it the instance you want it to work with.

    Like so:

    class enclosing
    {
    protected:
        int var1 = 2;
        int var2 = 4;
    public:
        friend class problem;
        class problem
        {
        public:
            void DoStuff(enclosing& e){
                int Sum = e.var1 + e.var2;
            }
        } i1;
    } e1;
    
    int main()
    {
        e1.i1.DoStuff(e1);
        enclosing e2;
        e2.i1.DoStuff(e1); // Also works
        enclosing::problem x;
        x.DoStuff(e2); // This, too.
    }