Click here to Skip to main content
15,125,104 members
Articles / Programming Languages / C++
Posted 5 Apr 2004


69 bookmarked

Generic Observer Pattern and Events in C++

Rate me:
Please Sign up or sign in to vote.
4.36/5 (19 votes)
5 Apr 20044 min read
Efficient and generic way to implement Events in C++. Easy and intuitive way to connect an event to any member function of any class with no limitations.


One of the interesting features I found in C# is a “Events and Delegates” concept. The idea is good but not new in Object Oriented Programming, it is one of the most frequently used concepts in programming, sometimes referred to as “Observer” or “Document/View” design pattern. Classical formulation of it could be found in “Design Patterns, Elements of Reusable Object Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (The Gang of Four).

This concept is used when you want some information stored in one object, called “model” (subject) to be watched by others, called “views” (observers). Each time when information is changed in the “model”, “views” attached to the model should receive notification and update there states accordingly to the changed “model”.

Classical implementation described in “Design Patterns”:

As it is seen from the class diagram, concrete models should be derived from Subject class and views from Observer. Any time the state of Subject is changed, it calls notify method which notifies all observers attached to the Subject.

void Subject::notify()
      for(int i=0; i<observes.size(); i++)

In many applications, this straightforward implementation is good enough, but things are getting ugly when you have different kinds of changes in the “subject” and you want to pass different types of parameters to the “views”.

One of the examples for complex “Model”/“View” relations is a GUI control attached to its processing function. Each time the control’s state is changed, process function is called with parameters indicating new state of the control.

These kinds of problems are solved in C# by the introduction of “Events and Delegates” concept. The resolution of the problem is easier in C#, because all classes are inherited from the same “object” class.

At the beginning, I thought why we do not have this nice “Events and Delegates” thing in standard C++, but then I came to the conclusion that C++ does not need it.

C++ language is powerful enough to express “Events” and “Delegates” concept in terms of already existing primitives. Proposed design makes it possible to "connect" different methods with different number of parameters belonging to unrelated classes to the “model”.

The keys for this solution are C++ templates (generic types) and pointes to member functions.

Using Code

Suppose we have a class MySubject that has internal information connected to different views, it produces three different types of events called int_event, double_event and triple_event with different types and numbers of parameters.

class MySubject

    CppEvent1<bool,int> int_event;
    CppEvent2<bool,double,int> double_event;
    CppEvent3<bool,double,int,const char*> triple_event;

    void submit_int()

    void submit_double()

    void submit_triple()
        triple_event.notify(10.5,100,"Oh ye");

Views represented by MyListener1 and MyListener2 are unrelated. The only requirement is for callback (delegate) methods to have parameters signature similar to corresponding CppEvent.

class MyListener1

    bool update_int(int p)
        Console::WriteLine(S"int update listener 1");
        return true;

    bool update_double(double p,int p1)
        Console::WriteLine(S"double update listener 1");
        return true;

    bool update_triple(double p,int p1,const char* str)
        Console::WriteLine(S"triple update listener 1");
        return true;

class MyListener2

    bool fun(int p)
        Console::WriteLine(S"int update listener 2");
        return true;

The final step is to create viewers MyListener1 and MyListener2 and connect their member functions to corresponding events in MySubject model.

int main(void)
        // create listeners (viewers)
    MyListener1* listener1 = new MyListener1;
    MyListener2* listener2 = new MyListener2;

        // create model
    MySubject subject;

        // connect different viewers to different events of the model
    CppEventHandler h1 = subject.int_event.attach(listener1,
    CppEventHandler h2 = subject.int_event.attach(listener2,

    CppEventHandler h3 = subject.double_event.attach(listener1,
    CppEventHandler h4 = subject.triple_event.attach(listener1,

    // generate events

    // detach handlers 

    return 0;

Resulting output is:

> int update listener 1
> int update listener 2
> double update listener 1
> triple update listener 1


First of all, if we want to attach different types of event handles (member functions with same types of parameters from different classes) to the same event, we should provide common base for them. We use templates to make it generic for any combination of parameter types in “delegate” or call back method. There are different event types for every number of arguments in callback function.

// Event handler base for delegate with 1 parameter
template <typename ReturnT,typename ParamT>
class EventHandlerBase1
    virtual ReturnT notify(ParamT param) = 0;

Specific type of member function pointer within a pointer to the object is stored in the derived class.

template <typename ListenerT,typename ReturnT,typename ParamT>
class EventHandler1 : public EventHandlerBase1<ReturnT,ParamT>
    typedef ReturnT (ListenerT::*PtrMember)(ParamT);
    ListenerT* m_object;
    PtrMember m_member;


    EventHandler1(ListenerT* object, PtrMember member)
        : m_object(object), m_member(member)

    ReturnT notify(ParamT param)
        return (m_object->*m_member)(param);

Event class stores map of event handlers and notifies all of them when notify method is called. Detach method is used to release handler from the map.

template <typename ReturnT,typename ParamT>
class CppEvent1
    typedef std::map<int,EventHandlerBase1<ReturnT,ParamT> *> HandlersMap;
    HandlersMap m_handlers;
    int m_count;


        : m_count(0) {}

    template <typename ListenerT>
    CppEventHandler attach(ListenerT* object,ReturnT (ListenerT::*member)(ParamT))
        typedef ReturnT (ListenerT::*PtrMember)(ParamT);
        m_handlers[m_count] = (new EventHandler1<ListenerT,
        return m_count-1;

    bool detach(CppEventHandler id)
        HandlersMap::iterator it = m_handlers.find(id);

        if(it == m_handlers.end())
            return false;

        delete it->second;
        return true;

    ReturnT notify(ParamT param)
        HandlersMap::iterator it = m_handlers.begin();
        for(; it != m_handlers.end(); it++)

        return true;


This implementation is quite similar to those in the article “Emulating C# delegates in Standard C++”. I found out it after I already wrote the article. Actually, the fact that we have a similar way to deal with the problem means that it’s a very intuitive solution for this kind of problem in C++. An advantage of the current implementation is that it supports different number of arguments, so any member function of any class could be a callback (delegate). Probably to have this thing as a part of standard library is a good thing, but even if it’s not a part of the standard, you can use it as it is. This implementation is restricted to events up to 3 parameters, it can be easily extended to other numbers by just rewriting it with different number of parameters (see code for details).


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Eduard Baranovsky
Web Developer
Canada Canada
Baranovsky Eduard has been a software developer for more then 10 years. He has an experence in image processing, computer graphics and distributed systems design.

Comments and Discussions

GeneralMy vote of 1 Pin
Member 806656624-Dec-12 3:22
MemberMember 806656624-Dec-12 3:22 
GeneralMy vote of 4 Pin
TERRY DEGLOW26-May-11 13:27
MemberTERRY DEGLOW26-May-11 13:27 
QuestionCompilation problem Pin
saturner6523-Aug-07 21:35
Membersaturner6523-Aug-07 21:35 
AnswerRe: Compilation problem [modified] Pin
GlennNZ14-Apr-09 1:22
MemberGlennNZ14-Apr-09 1:22 
Generalsignal-slot Pin
hslew3-Sep-06 11:48
Memberhslew3-Sep-06 11:48 
GeneralRe: signal-slot Pin
Eduard Baranovsky5-Sep-06 4:26
MemberEduard Baranovsky5-Sep-06 4:26 
Generalsome design issue in the code Pin
Xiaotian Guo16-Jul-04 10:20
MemberXiaotian Guo16-Jul-04 10:20 
GeneralRe: some design issue in the code Pin
Eduard Baranovsky19-Jul-04 5:56
MemberEduard Baranovsky19-Jul-04 5:56 
GeneralRe: some design issue in the code Pin
Eduard Baranovsky14-Sep-04 8:56
MemberEduard Baranovsky14-Sep-04 8:56 
GeneralNice Pin
Patje8-Apr-04 22:13
MemberPatje8-Apr-04 22:13 
GeneralRe: Nice Pin
Eduard Baranovsky14-Sep-04 9:46
MemberEduard Baranovsky14-Sep-04 9:46 
GeneralRe: Nice Pin
Patje14-Sep-04 23:02
MemberPatje14-Sep-04 23:02 
GeneralRe: Nice Pin
Member 1019550528-Oct-17 5:01
professionalMember 1019550528-Oct-17 5:01 
GeneralLink to article &quot;Emulating C# delegates in Standard C++&quot; Pin
Uwe Keim6-Apr-04 20:20
sitebuilderUwe Keim6-Apr-04 20:20 
QuestionSome memory leaks? Or is this managed C++? Pin
Don Clugston6-Apr-04 14:48
MemberDon Clugston6-Apr-04 14:48 
AnswerRe: Some memory leaks? Or is this managed C++? Pin
Eduard Baranovsky7-Apr-04 4:53
MemberEduard Baranovsky7-Apr-04 4:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.