1

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?

DVSProductions
  • 77
  • 1
  • 13

2 Answers2

1

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.
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

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;
        }
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335