1

I would like to assign a class member function to a function pointer.

Here's my simple example:

#include <iostream>

typedef void (*func_t)(void);
static func_t funcPtr;

class Foo {
public:
    Foo() {
        funcPtr = (func_t)callback;
    }
    void callback() {
        std::cout << "callback called\n";
    }
};


int main() {
    Foo foo;
    funcPtr();
}

But I get the following error:

Cannot cast from type 'void' to pointer type 'func_t' (aka 'void (*)()')

If I simply make the callback() function static, then it works fine.

But I would like to leave it as a non-static member function.

How can I assign the callback() function to a funcPtr?

Zack Lee
  • 2,784
  • 6
  • 35
  • 77
  • You can't do that. The closest thing you can do is to have a `static` instance of `Foo`, and a non-member of static function that calls `callback()` on it, which can then be converted to a pointer. – HolyBlackCat Aug 09 '20 at 12:16

0 Answers0