I want to create an event dispatch system with a (shallow) hierarchy of Events that can be observed by a (shallow) hierarchy of EventObservers. I figured double-dispatch would allow a wide variety of both Events and EventObservers without having to have a function for every single combination.
I have code like this:
class BaseObserver;
class BaseEvent {
public:
virtual std::string getName() { return "BaseEvent"; }
void beObservedBy( BaseObserver* obv );
};
class BaseObserver {
public:
virtual void observe( BaseEvent* evt ) {
std::cout << "BaseObserver observing: " << evt->getName() << "." << std::endl;
}
};
void BaseEvent::beObservedBy( BaseObserver* obv ) { obv->observe( this ); }
Then define a few test classes:
class EventA : public BaseEvent {
public:
void beObservedBy( BaseObserver* obv ) { obv->observe( this ); }
virtual std::string getName() { return "I am an EventA"; }
};
class EventB : public BaseEvent {
public:
void beObservedBy( BaseObserver* obv ) { obv->observe( this ); }
virtual std::string getName() { return "I am an EventB"; }
};
class ObserverX : public BaseObserver {
virtual void observe( EventA* evt ) { std::cout << "ObserverX spotted an EventA" << std::endl; }
};
(This was all following the lead of Double dispatch/multimethods in C++ and the Wikipedia article on double dispatch )
Now when I debug the double-dispatch, the beObservedBy
method of the derived Event class (EventA
, say) is called, and the derived EventObserver class is used, but the observe( BaseEvent* )
function is called rather than the observe( EventA* )
Am I doing it wrong? I tried with using references instead of pointers and got no love.