I am just showing different use cases, I am not saying than the 1st
example is better than the 2nd one (or vice versa), but the latter is
very common, for example, in GUI applications... your Window/Dialog
class handles the events from the contained widgets. You can use free
functions as event handlers, but member functions has the context of the
parent class (of course, std::bind is very powerful so you can add the
context to your free functions if you want), i.e:
class MyWindow: public Window {
Button okCancel;
EditBox name;
EditBox address;
SomeWindowContext context;
void onClick(Button& button) {
if (button.isCancel()) {
...
}
else {
...
}
}
void onFocus(EditBox& editBox) {
// Use window's context here
}
void onLostFocus(EditBox& editBox) {
// Use window's context here
}
void initWidgets() {
...
okCancel.onClick = std::bind(&MyWindows::onClick, this, _1);
// For simplicity, callbacks are reused for similar widgets
name.onFocus = std::bind(&MyWindows::onFocus, this, _1);
name.onLostFocus = std::bind(&MyWindows::onLostFocus, this, _1);
address.onFocus = std::bind(&MyWindows::onFocus, this, _1);
address.onLostFocus = std::bind(&MyWindows::onLostFocus, this, _1);
...
}
public:
MyWindow(...): ... {
initWidgets();
}
void show() {
...
}
};
C# uses the same scheme via delegates (the .Net std::function
counterpart). Java used to have a similar approach in Swing, but
anonymous classes were used to redirect a widget event to the parent
class callback. In modern C++ we can use a lambda to code the event or
to redirect it to the parent class. There are a lot of approaches, all
of them with pros and cons.
Usually, the initWidget member function (initializeComponent/jbInit in
C#/Java) are managed by the GUI editor/IDE, so the event connection (as
well as the widget configuration) is automatic. In the old days of MFC,
a message map built with macros was the initWidget equivalence. The map
was managed by the Class Wizard (*) tool.
I use the past tense to talk about MFC because my last contact with it
was 16 years ago :-O but I think Class Wizard (and the message map)
still exist.