Whoops, perhaps I should have made the example a bit more complete.
I was just focusing on reproducing the syntax you contrived, and not runtime.
I don't think this will crash, but it's really just a contrived example so it isn't really useful:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
// Example program
#include <iostream>
struct Foo1 {
// A Foo1 contains a Foo2 (with foo2 pointer and object being made)
// A Foo2 contains a Foo3 (with foo3 pointer and object being made)
// A Foo3 contains a foo4 member function
struct Foo2 {
struct Foo3 {
void foo4() { std::cout << "printing foo4\n"; };
};
Foo3 foo3_obj;
Foo3* foo3;
};
Foo2 foo2_obj;
Foo2* foo2;
};
int main()
{
Foo1 foo1_obj;
Foo1* foo1 = &foo1_obj;
foo1->foo2 = &foo1->foo2_obj;
foo1->foo2->foo3 = &foo1->foo2->foo3_obj;
foo1->foo2->foo3->foo4();
}
|
Another example:
For a program with a GUI, you might run into a design issue where you have something like this:
A is the main window, and B and C are sub-components of the window.
What if C needs to communicate some result or feedback to B? Should we directly link B to C? Maybe, but another way of doing it is for B to make a call back to A, and then A knows that it needs to update B.
Or, perhaps C has a pointer to A (m_parent), we can do something like this:
1 2 3 4
|
void C::func()
{
this->m_parent->b_child->doThing();
}
|
Lots of indirection! But, in this way, (C) still knows about (B), but not directly, since it's still doing the action through the parent (A). I'm not sure if this is the best way of doing things, but I've definitely seen it in code.