Function pointer as parameter

115,411

Solution 1

The correct way to do this is:

typedef void (*callback_function)(void); // type for conciseness

callback_function disconnectFunc; // variable to store function pointer type

void D::setDisconnectFunc(callback_function pFunc)
{
    disconnectFunc = pFunc; // store
}

void D::disconnected()
{
    disconnectFunc(); // call
    connected = false;
}

Solution 2

Replace void *disconnectFunc; with void (*disconnectFunc)(); to declare function pointer type variable. Or even better use a typedef:

typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
    fptr = func;
}

void D::disconnected()
{
    fptr();
    connected = false;
}

Solution 3

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Share:
115,411
Roland Soós
Author by

Roland Soós

Updated on February 20, 2020

Comments

  • Roland Soós
    Roland Soós about 4 years

    I try to call a function which passed as function pointer with no argument, but I can't make it work.

    void *disconnectFunc;
    
    void D::setDisconnectFunc(void (*func)){
        disconnectFunc = func;
    }
    
    void D::disconnected(){
        *disconnectFunc;
        connected = false;
    }
    
  • Roland Soós
    Roland Soós about 14 years
    Thank you. Final code: void (*disconnectFunc)(); void D::setDisconnectFunc(void (*func)()){ disconnectFunc = func; } void D::disconnected(){ (*disconnectFunc)(); connected = false; }
  • Dan
    Dan about 14 years
    +1 for using my preferred syntax of de-referencing a function pointer (prefer disconnectFunc() to (*disconnectFunc)(), even though they're both fine)
  • JavaRunner
    JavaRunner almost 11 years
    Is this portable way or it's not recommended to use for portability?
  • GManNickG
    GManNickG almost 11 years
    @JavaRunner: It's perfectly portable.
  • JavaRunner
    JavaRunner almost 11 years
    Fine. Thanks! Do you happen to know what I need to fix in that code if I need to pass function to setDisconnectFunc() with some parameters?
  • GManNickG
    GManNickG almost 11 years
    @JavaRunner: You should ask a new question if you need help extending it, the comment section is too constrained. There are many ways to do it, whatever your requirements are.
  • gihanchanuka
    gihanchanuka almost 9 years
    Putting this into a simple form with more understandable manner 1. learncpp.com/cpp-tutorial/78-function-pointers 2. newty.de/fpt/fpt.html (also about how to return a function pointer)