Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ nested classes, access fathers variables [duplicate]

The title already says a lot,

but basically what i want to do is the following(Example):

I have a class called A, and another class inside a called B, like so:

class A
{
   int a;

   class B
   {
      void test()
      {
         a = 20;
      }
   };
};

As you can see my goal is for class B to have access to class A, as it is a nested class. Not this wont work, because B doesn't have access to A, but how can it get access?

Thank You

like image 616
Miguel P Avatar asked Oct 11 '12 21:10

Miguel P


2 Answers

Despite that you declared class B inside of A, classes A and B are still completely independent. The only difference is that now to refer to B, one must do A::B.

For B to access A's stuff, you should use composition or inheritance. For composition, give B a reference to an object of A, like so:

class B {
public:
  B(const A& aObj) : aRef(aObj) {
    cout << aRef.a << endl;
  }
private:
  const A& aRef;
};

For inheritance, something like this:

class B: public A { // or private, depending on your desires
  B() {
    cout << a << endl;
  }
}
like image 177
Philip Avatar answered Sep 30 '22 00:09

Philip


The inner class is not related to the outer class in C++ as it is in Java. For an instance of A::B to access a member of an A object, it needs to have an instance of A somewhere, just as if B were not a nested class. Instances of A::B do not have any implicit instance of A; you can have many instances of A::B without any instances of A existing at all.

Pass an instance of A to test, and then use it to access the a member:

void test(A& a_instance)
{
  a_instance.a = 20;
}
like image 39
Rob Kennedy Avatar answered Sep 30 '22 00:09

Rob Kennedy