What's the c++ convention for monitoring parameter changes?

I'm trying to figure out the C++ way of implementing a programming pattern that I use in Java.

I have a class that represents a view of my data used by the UI, and it wraps another class that contains the data my program is operating on (ie, model/view programming pattern). With this paradigm, while my view class can know details of the design of my model class, the model class should be independent of (ie, ignorant of) the view. I'm trying to figure out how to have my model alert the view that it has changed its state and that the view should rebuild itself.

In Java this is pretty straight forward with listeners, but C++ doesn't have those. Is there some convention C++ uses for this situation?

Last edited on
You could register a callback function with the model, which is presumably what your "listener" is in java.

Here's an example. (Hopefully JLBorges will see your post and provide a nicer version.)

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
#include <iostream>

class Model {
    int n;
    void(*callback_func)();
public:
    Model(void(*cf)())
        : n(), callback_func(cf) {}
    int get() const { return n; }
    void set(int m) {
        n = m;
        if (callback_func) callback_func();
    }
};

class View {
    const Model& model;
public:
    View(const Model& model) : model(model) {}
    void render() {
        std::cout << model.get() << '\n';
    }
};

View *g_view;
void callback_func() { g_view->render(); }

int main() {
    Model model(callback_func);
    View view(model);
    g_view = &view;
    model.set(24);
    model.set(42);
}

Qt has what it calls "signals". And model/view: https://doc.qt.io/qt-5/modelview.html

Not sure if those count as Observer pattern: https://en.wikipedia.org/wiki/Observer_pattern
I'm trying to avoid using Qt's signals and slots for my model code. You need to extend QObject to use it and that imposes restrictions on what you can do, so I'm trying to keep classes that extend it only in the UI code.

Using a callback of some sort seems to be the way to go. Thanks for the suggestions.
I did not say "use Qt". I said that Qt (written in C++) use that method for that situation.

Note that boost.signals2 implements the same idea: https://en.wikipedia.org/wiki/Signals_and_slots#Alternative_implementations

I can't say whether signals and slots are (de facto) convention that C++ uses, but you can look into Qt and boost to see how they implement it.
Sounds like the MVC model-view-controller pattern is relevant and this is what jlborges had to say on it:

http://www.cplusplus.com/forum/beginner/169892/#msg848732
Registered users can post here. Sign in or register to post.