c++ – How do I pass a function as a parameter in C ++?

Question:

How to declare all this and then get the return value?

Answer:

Function:

int MyFunction(int a){ printf("Hi!\n");   return 2*a; }

We declare:

int (*pt2Func)(int ) = NULL;

Let's initialize the pointer:

pt2Func = &MyFunction;

We pass it to the function and use:

void PassPointer(int (*pt2Func)(int )) {
   int result = (*pt2Func)(12); 
   cout << result << endl;
}
Scroll to Top