Is there a C++/OOP alternative to callback functions?

I wrote a class that represents a gui window. When an event occurs in the window, like mouse input, what is the C++ way of notifying code outside the class of the event? Currently I use function pointers, which I understand now is the C way of doing it.
Last edited on
I think it actually depends on the API you are using. Qt uses slots and signals whith is more C++-like.

Aceix.
Well I use the WINAPI directly so there are no slots and signals, just the window procedures. I want to implement an event system without relying on other libraries.
closed account (z05DSL3A)
Observer pattern?
http://en.wikipedia.org/wiki/Observer_pattern
Well, if you're wanting to go it alone, you could possibly switch from callback functions to callback interface (or "interface") classes? (see "example" below...) But that doesn't address how you hook-up and route the events. That might lead you to implement your own version of signals and slots, I guess.

And delegates are also something to consider; the version that started off life as Boost.Function and made it into TR1 is now part of C++11, as std::function.
http://en.cppreference.com/w/cpp/utility/functional/function
(couldn't spot a cplusplus.com ref?) And there is quite a bit of forum (etc) chatter about fast C++ delegates, e.g.

Lightweight Generic C++ Callbacks (or, Yet Another Delegate Implementation)
http://www.codeproject.com/Articles/136799/Lightweight-Generic-C-Callbacks-or-Yet-Another-Del

Andy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

class IExample {
public:
    virtual void OnTest() = 0;
};

class Foo {
private:
    IExample* m_pCallback;

public:
    Foo() : m_pCallback(0) {
    }

    void SetCallback(IExample* pCallback) {
        m_pCallback = pCallback;
    }

    void Test() {
        if(m_pCallback) {
            m_pCallback->OnTest();
        }
    }
};

class Bar : public IExample {
public:
    /*virtual*/ void OnTest() {
        cout << "Hello world!" << endl;
    }
};

int main() {
    Foo foo;
    Bar bar;

    foo.SetCallback(&bar);
    foo.Test();
    foo.SetCallback(0);

    return 0;
}
Last edited on
Topic archived. No new replies allowed.