Function pointer as parameter

Roland Soós picture Roland Soós · Apr 6, 2010 · Viewed 100k times · Source

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;
}

Answer

GManNickG picture GManNickG · Apr 6, 2010

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;
}