Axel
Axel

Reputation: 454

C++ Pass a member function to another class

I'm trying to make a simple callback in C++ but I'm having issues doing it as I want to.

Essentially I want something like this:

class A{
   void A::AddCallback(void (*callBackFunction)(string)){
      /*Code goes here*/
   }
}

And class B

#include "A.h"
class B{
   B::B(){
      A childObject;
      childObject(MyCallBackFunction);   
   }
   B::MyCallBackFunction(string arg){
      /*Code goes here*/
   }
}

I know that usually you would want to define the header of AddCallback with something like B::callBackFunction but I do need to import A in B so I it would be awkward to have both classes import each other. I know I've seen this before but I cant get the syntax right

Upvotes: 5

Views: 2724

Answers (2)

meet thakkar
meet thakkar

Reputation: 84

you must call void A::AddCallback and pass callback instead of passing argument in childObject(MyCallBackFunction);

Upvotes: -1

Kerrek SB
Kerrek SB

Reputation: 476940

Here is one option using a static member function:

#include <string>

struct A
{
    void AddCallback(void (*cb)(std::string));
};

struct B
{
    A a;

    B() { a.AddCallback(&B::MyFun); }

    static void MyFun(std::string);
};

If you want a non-static member function, then you first need to decide on which instance of B you want the member function to be invoked. For example, to invoke it on the object whose constructor registers the callback:

#include <functional>
#include <string>

struct A
{
    void AddCallback(std::function<void(std::string)>);
};

struct B
{
    A a;

    B() { a.AddCallback(std::bind(&B::MyFun, this, std::placeholders::_1)); }

    void MyFun(std::string);
};

Upvotes: 7

Related Questions