Link to home
Start Free TrialLog in
Avatar of Unimatrix_001
Unimatrix_001Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Inner class accessing outer class private variables.

Hi.

class ClassA{
      public:
            class ClassB{
            }
      private:
            int aVar;
}

How can I allow the methods of classB to use the variable in class A in a tidy fashion?

Thanks,
Uni
SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Inner classes are allowed to access Outer class private variables. They just treated as methods.

Just make sure, that inner class' methods are defined after outer class variables definition.
And of course inner class have to have reference(pointer) to instance of superclass.
Hi Unimatrix_001,

It only makes sense to declare a nested (or inner) class if you instantiate the inner class.

class ClassA{
      public:
            class ClassB{
            }
      private:
            classB *B;
            int aVar;
}

Now your options are wide open.  You can pass aVar to the classB instantiator which saves it in the inner class, or pass it to a method in the inner class.

ClassA  *A;

  A = new ClassA;
  A->B = new ClassB;


Good Luck,
Kent
Avatar of Unimatrix_001

ASKER

Hi Zoppo: Thanks for that, although I can't pass an instance as what I'm wanting int classA is static...
Kent: The reason for the nested class is to seperate certain methods in classA from other methods in classA while keeping all the methods within classA... That sounds a bit of a mouthful, but nevertheless there is logical reasoning behind it. ;)
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hehe, it does seem a bit of a muddle... Still, it seem that's the only way to do it.

Thanks :)
Uni.