what I don't get is why I would ever need to do this
I think you never need to do this. Given a nested class like this ...
class A
{
//B is used to help implement A
class B
{
...etc...
}
...etc...
}
... you can always move the inner/nested class to global scope, like this ...
class A
{
...etc...
}
//B is used to help implement A
class B
{
...etc...
}
However, when B is only used to help implement A, then making B an inner/nested class has two advantages:
friend
keyword).When I say that B can access private members of A, that's assuming that B has a reference to A; which it often does, since nested classes are often declared like this ...
class A
{
//used to help implement A
class B
{
A m_a;
internal B(A a) { m_a = a; }
...methods of B can access private members of the m_a instance...
}
...etc...
}
... and constructed from a method of A using code like this ...
//create an instance of B, whose implementation can access members of self
B b = new B(this);
You can see an example in Mehrdad's reply.