C++ Pointer to a function

A pointer to a function in C++ is a variable that stores a function’s memory address. Pointers to functions can be used to store functions in data structures like arrays or linked lists as well as to return functions from other functions and give them as arguments to other functions.

Syntax:

return_type (*pointer_name)(parameter_list);

Example:

#include <iostream>
using namespace std;

int add(int a, int b) {
   return a + b;
}

int subtract(int a, int b) {
   return a - b;
}

int operate(int a, int b, int (*func)(int, int)) {
   return func(a, b);
}

int main() {
   int a = 5, b = 3;
   int result1 = operate(a, b, add);
   int result2 = operate(a, b, subtract);
   cout << "The sum is: " << result1 << endl;
   cout << "The difference is: " << result2 << endl;
   return 0;
}

Output:

The sum is: 8
The difference is: 2

In this illustration, the functions add and subtract each take two integer arguments and return an integer. Two integers plus a pointer to a function that accepts two integers and returns an integer are the third input to the operate function. Using the two numbers as parameters, the operate function calls the function pointed to by func and returns the outcome.

Operate is called twice in the main function, once with add and once with subtract as the function arguments. The outcomes are printed to the console and stored in result1 and result2, accordingly.