Function pointer as parameter

C++FunctionPointersFunction Pointers

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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 - C++

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

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

Solution 3 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoland SoósView Question on Stackoverflow
Solution 1 - C++GManNickGView Answer on Stackoverflow
Solution 2 - C++Nikolai FetissovView Answer on Stackoverflow
Solution 3 - C++WhirlWindView Answer on Stackoverflow