DVSProductions
DVSProductions

Reputation: 87

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?

Upvotes: 1

Views: 683

Answers (2)

molbdnilo
molbdnilo

Reputation: 66459

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

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

The data members have to be accessed via an object of the enclosing class. For example

void DoStuff( const enclosing &e){
            int Sum = e.var1 + e.var2;
        }

Upvotes: 0

Related Questions