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; }
Pointer as a function parameter is used to hold addresses of arguments passed during function call. This is also known as call by reference. When a function is called by reference any change made to the reference variable will effect the original variable.
Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.
The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
Passing a function as a parameter in C++ Passing pointer to a function: A function can also be passed to another function by passing its address to that function.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With