5

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

Axel
  • 414
  • 1
  • 7
  • 21
  • The last part suggests you want to know how to solve circular dependency issues as well; if so, see the ends of these answers: http://stackoverflow.com/a/628079/5386374 & http://stackoverflow.com/a/4757718/5386374 [Specifically: If A.h doesn't need to know B's internal details, forward declare `B` in `A.h`, `#include "B.h"` in `A.cpp`, & `#include "A.h"` in `B.h`. If B.h doesn't need to know A's, forward declare `A` in `B.h`, `#include "A.h"` in `B.cpp`, & `#include "B.h"` in `A.h`. Or both: forward declare `A` in `B.h`, forward declare `B` in `A.h`, & put `#include`s in the `.cpp` files.] – Justin Time - Reinstate Monica Feb 26 '16 at 01:29

2 Answers2

7

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);
};
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
-1

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