Search code examples
c++callbackfunction-pointersboost-function

C++: How do I pass a pointer to a member function of another class?


How would the signature for function Foo() fo class classA have to look when I want to pass a pointer to a function that is a member of classB? Function update() is called on an isntance of classB and gets passed an object of classA. Inside update() the function Foo() of classA shall be passed a pointer to a callback function. That function is a member of classB. I can't make anything static here. Is there a way to do this, maybe with boost::function ?

Code:

class classA
{
 public:
  voif Foo(/*a pointer to a memberfunction of ClassB*/)
};

class classB
{
 classB(){nVal = 0;}
 int nVal;
 public:
 void increment(int n){nVal += n;}
 void update(classA objA)
 {
  objA.Foo(increment)
 }
};

Solution

  • You can use boost::bind with boost::function.

    class classA
    {
    public:
       void Foo(const boost::function<void(int)>& function)
       {
       }
    };
    
    class classB
    {
    public:
       //
       void update(classA objA)
       {
           objA.Foo(boost::bind(&classB::increment, this, _1));
       }
    };