I am new to pointer to member functions, and I would like to know their pros and cons.
Specifically, consider this:
#include <iostream>
#include <list>
using namespace std;
class VariableContainer;
class Variable
{
public:
Variable (int v) : value (v), cb_pointer (0) {}
~Variable () {}
void SetCallback (void (VariableContainer::*cb)(int)) {
cb_pointer = cb;
}
void FireCallback (void) {
/* I need a reference to a VariableContainer object! */
}
private:
int value;
void (VariableContainer::*cb_pointer) (int);
};
class VariableContainer
{
public:
VariableContainer () {}
~VariableContainer () {}
void AddVar (Variable &v) {
v.SetCallback (&VariableContainer::Callback);
}
void Callback (int v) { cout << v << endl; }
};
int main ()
{
Variable v (1);
VariableContainer vc;
vc.AddVar (v);
v.FireCallback();
return 0;
}
As stated in the comment, to trigger the callback (FireCallback
) I need some reference to an existing VariableContainer
object, which should be provided as an additional argument of VariableContainer::AddVar (...)
.
Now:
- Should I use the pointer to member function? Or should I call directly
Callback (...)
(since I have a pointer to theVariableContainer
object)? - What are the advantages and drawbacks of each solution?
TIA, Jir