Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to passing a pointer to yourself to objects you own

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?)

like image 477
johnbakers Avatar asked Apr 10 '13 06:04

johnbakers


2 Answers

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).

like image 70
Mikkel Avatar answered Nov 20 '22 00:11

Mikkel


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

like image 2
maditya Avatar answered Nov 19 '22 23:11

maditya