C++ Design – Best Design for Callback Implementation in C++

cobject-oriented-design

I have a class "Parent". "Parent" class creates an object of class "Child" in my CPP module.
The use-case is "Child" has to request for some information from "Parent". This can be done in several ways and I can think of the following designs.

1) Store object pointer/reference of "Parent" in "Child" and let "Child" call some public method of "Parent".

2) "Child" exposes an API to register callbacks. "Parent" registers a static function with "this" pointer as callback handle. When "Child" wants to request for information, it will call the registered callback function with callback handle as one of the arguments. The callback function will dereference the callback handle to "Parent" object and get the information.

Can someone tell me which is the better design? Also I would like to know is there any standard design for this type of problem?

Best Answer

It probably depends on how tightly you want your objects to be coupled. But for faster development and more readable code I think the method 1 is preferable. Just store the reference to parent as a weak pointer (assuming you use modern C++).

You could do some pattern in which the parent would register a function within the child (in this case prefer closures and std::function to bare function pointers). But if these two objects are the only ones that will need to share the information then I see no point of not giving a pointer to parent to the child object, this is used quite often.

Finally, best would be to have a uni-directional data flow if it is possible. Rather than making the child ask for information, make the parent push it inside. This will make the interface more readable and safe (because the parents always knows whether it is safe to send data but the child might not be aware of the parent's state). It also makes it easier to have all data passed as constant values.