This question already has an answer here:
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
Classes are types, types don't have data. Instances have data, but an instance of
A
does not (in your example) contain an instance ofB
, and the instances ofB
don't have any knowledge of any instance ofA
.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:
For inheritance, something like this:
C++ nested classes are not like java nested classes, they do not belong to an instance of A but are static. So a doesn't exist at that point
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 anA
object, it needs to have an instance ofA
somewhere, just as ifB
were not a nested class. Instances ofA::B
do not have any implicit instance ofA
; you can have many instances ofA::B
without any instances ofA
existing at all.Pass an instance of
A
totest
, and then use it to access thea
member:Choices
B
be a child ofA
instead of contained byA
B
's constructor take a ref to theA
instance which created it (preferred)Now, if the variable
a
is private this still won't help. You will either need an accessor a or a friend relation.