Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer as parameter

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; } 
like image 541
Roland Soós Avatar asked Apr 06 '10 01:04

Roland Soós


People also ask

How are pointers used as function parameters?

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.

Can we pass pointer to a function as parameter?

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.

How do you call a function pointer?

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.

Can you put a function as a parameter?

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.


1 Answers

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; } 
like image 142
GManNickG Avatar answered Sep 22 '22 02:09

GManNickG