Design – Calling Back to Parent Class

clanguage-agnosticobject-oriented-design

When modelling an object with children it's common to include the children via composition, as a member of the parent class. Sometimes however the children need to tell the parent something, they need to call a function of the parent. How can this be accomplished using C++? Some options are:

  1. Make the parent class global therefore the child objects will be able to call member functions of the parent object.

  2. Inject the parent object as a, pointer or reference, into every child object. Then when the child needs to tell the parent object something, it can always do so because it has a member variable that it can use.

What are other methods of doing this? Is there a general design pattern or name for this sort of thing?

Note that I'm interested in ideas and solutions in C++ because the details are going to be different in other object-oriented languages. For example point 2 above mentions 'pointers or references' and both are only possible in C++. C++ has language features that are not present in other languages therefore implementations of a solution to the problem will potentially incorporate these language features making the solution different from what someone might come up with in another language.

Best Answer

First things first, this can be a code smell. The point of using composition for the parent/children is that the parent knows about the children but not vice versa. Especially if the relation is more of a 'contains' than 'is composed of'.

A reference to the parent is possible and fairly common in C++. In other languages, a function object or event is more often used to allow the child to communicate things that outsiders might want to know. This is a common publish-subscriber sort of pattern. I suspect that which is more idiomatic depends on which version of C++ you're using and the standards of your codebase.