I am trying to improve my knowledge on program architecture and recently arised a question to me which is related with this pointers issues I posted recently.
The thing is that in a simple hierarchy in which you have Class A with a pointers to Class B and the last to Class C. Do not confuse the with the inheritage property of the Object Oriented programming but basically what I am saying is that Class C is the child of Class B and Class B is the child of Class A.
The point is that I want to be able to access directly from Class A to Class C (the grandson in the analogy) with pointers. Some other members pointed out this is poor design, basically because if a delete an instance of class C from class B collection would leave a pointer to “nothing” in the Class A collection. Then, how is this modelled properly?
Thank you a lot!
Julen.
Instead of making class A aware of every class C, consider using the Composite Pattern:
This program outputs:
Note that when
bike.print()is called,printis called recursively on all children. This is how you can perform operations on all children without the grand-parent knowing about all its children.The Visitor Pattern works very well with the Composite pattern, so I suggest you read up on that one too. Especially if you have many operations that can be implemented in terms of more basic ones.