Steve Keller writes:
> I find myself often in a situation where a class or struct contains
> other classes/structs, both have member functions and I want to access
> members of the inner class from the outer class or vice versa:
>
> struct A {
> int x;
> struct B {
> int y;
> void bar() {
> // I want to access A's member x here
> }
> } b;
> void foo() {
> // I can access B's member y here. But can I somehow
> // do so using only y without the b. in front?
> b.y;
No. The only reason foo() can refer to x directly because x is a part of
this→.
> I could access b.y from A:foo() as only y if I add
>
> int &y = b.y;
Correct, that's how you'd do it.
> in struct A {}; but that adds a pointer to A and an additional pointer
> indirection with each access to b.y.
No, this doesn't add any pointer to any A. Additionally, you'll find out
that the resulting code will end up being identical to referencing b.y
explicitly, at least with moderate compiler optimizations enabled.
> But I can live with using b.y
> instead while only y would be more beautiful in this case.
Either way, the resulting code will be identical.
> To access a.x from B::bar() the only clean way I've found is to add a
> pointer to A in B and init it the constructor of A using 'this'. Like
Correct.
> struct A {
> int x;
> struct B {
> B(A *p) : parent(p) {}
> A *parent;
> void bar() { parent->x; }
> };
> A() : b(this) {}
> };
>
> But I'd like to avoid the pointer indirection, since the offset of B
> in A is known at compile time. Is that possible?
Of course not, because C++ does not work like that. A given instance of "B"
has nothing, whatsoever, to indicate which given instance of A it's a member
of.
A a1;
A a2;
A::B b;
b.bar();
For a plain "x" referenced in bar(), which A do you expect to be accessed,
a1 or a2 here, and why exactly? Please be specific in your answer.