Search code examples
c++function-pointers

C++ passing function pointer


I have the following function

static void p (){

}

I want to pass a function pointer to p into function x.

void x(void * ptr){

}

I am trying the following, and it is not working.

...
x(ptr);

Note x and p are in different classes. I am getting the following compiling error.

invalid conversion from 'void (*)()' to 'void*' [-fpermissive]

Solution

  • It needs to be:

    void x(void(*function)())
    {
      // Whatever...
    }
    

    If you're using C++11 you can std::function:

    void x(std::function<void()> function)
    {
      // Whatever
    }