I do this a lot:
class Child{
Control*parent;
public:
Child(Control*theParent):parent(theParent){}
};
class Control{
Child child;
void makeChild(){ child=Child(this); }
//Control() : child(this) { } //another example
}
So the Control owns and operates the child, but the child still has reference to the parent Control.
When I read general topics on program design patterns, etc, it seems like this method of organizing objects is not particularly recommended. I realize there are risks, for example you don't want your child
to abuse its parent by making its parent do things that only the parent should decide to do on its own; in which case, seems easy to prevent by making sure the parent's critical methods are private. But then you might have another controller that manages the parent, in which case some methods should be public, and now your child has access to those too, when really only some other controller should manipulate those.
So I can see how this can be dangerous.
But my question is, what is a common alternative? You need a parent to own a child, but you need the child to be able to notify the parent of things occasionally. How, if not the above?
Objective-C has the NSNotificationCenter which allows notifications without actually passing references, but this also makes it easy to create organizational problems (why is my child sending out this notification, and who is going to receive it?)
You can separate them by an interface:
class IListener {
public:
virtual void notify (int somevalue) = 0;
~IListener() {};
}
class Child{
private:
IListener *listener;
public:
Child(IListener *theListener):listener(theListener){}
};
class Control: public IListener {
private:
Child child;
public:
makeChild(){ child(this) };
virtual void notify(int someValue) { doSomething(someValue);};
}
(This is a simple version of the observer pattern, BTW).
It sounds like you are looking for the observer pattern.
In the observer pattern, an object maintains a list of dependents (aka observers) and notifies them of changes as required. In your case, the Control
class is the observer and the Child
class is the notifier.
The Boost library has a signal/slot mechanism that can be used to implement this: http://www.boost.org/doc/libs/1_49_0/doc/html/signals/tutorial.html#id3137144
There's an example of using this on SO: Complete example using Boost::Signals for C++ Eventing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With