Skip to main content
2 of 2
added 698 characters in body
Majenko
  • 105.9k
  • 5
  • 82
  • 139

Unless you specifically limit yourself to one single class for a callback (i.e., include the class name in the function pointer specification) then you can ONLY use static member functions as callbacks.

static member functions appear as a normal function, not a member function, so don't have the implied MyClass *this as a first parameter.

If you want to allow member functions that aren't static you will have to make use of polymorphism and have a single base class that all classes which provide a callback function will inherit from. Then you limit the callback function pointer to be members of that base class.

It is possible to do it if you are happy to limit to just one class, though the syntax is rather cryptic:

class MyClass 
{
  const byte theAnswer = 42;
  void (MyClass::*myCallback)();

public:

  void call() {
    (this->*myCallback)();
  }

  void setCallback(void (MyClass::*callback)()) {
    myCallback = callback;
  }

  void print_info() {
    Serial.println(theAnswer);
  }

  MyClass() {
    setCallback(&MyClass::print_info);
  }
};

Using polymorphism you can only pass a callback function that is a member of the parent class, so it looks like that method may be out.

Majenko
  • 105.9k
  • 5
  • 82
  • 139