A function pointer is a pointer that points to a function. This allows functions to be passed as arguments to other functions, stored in arrays, or assigned to variables. Function pointers are useful for implementing callback functions, dynamic dispatch, and more.
Here’s a complete program that demonstrates the use of function pointers in C++
#include <iostream>
using namespace std;
// Functions to be used with function pointers
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a – b;
}
// Function that takes a function pointer as a parameter
void performOperation(int x, int y, int (*operation)(int, int)) {
cout << “Result: ” << operation(x, y) << endl;
}
int main() {
// Declare function pointers
int (*funcPtr1)(int, int) = add;
int (*funcPtr2)(int, int) = subtract;
// Use function pointers to call functions
cout << “Using function pointers directly:” << endl;
cout << “Addition: ” << funcPtr1(10, 5) << endl; // add(10, 5)
cout << “Subtraction: ” << funcPtr2(10, 5) << endl; // subtract(10, 5)
// Use function pointers as arguments to another function
cout << “\nUsing function pointers as arguments:” << endl;
performOperation(20, 10, add); // add(20, 10)
performOperation(20, 10, subtract); // subtract(20, 10)
return 0;
}
Explanation of the Program
-
Function Definitions
We define two functions, ‘add’ and ‘subtract’, which perform addition and subtraction, respectively.
-
Function Pointer Declaration
We declare two function pointers, ‘funcPtr1’ and ‘funcPtr2’, and assign them to the ‘add’ and ‘subtract’ functions, respectively.
-
Calling Functions via Function Pointers
We use the function pointers to call the functions ‘add’ and ‘subtract’ directly.
-
Function with Function Pointer as Parameter
The ‘performOperation’ function takes two integers and a function pointer as parameters. It calls the function pointed to by ‘operation’ and prints the result.
-
Using Function Pointers as Arguments
We pass the ‘add’ and ‘subtract’ functions as arguments to the ‘performOperation’ function, demonstrating the flexibility of function pointers.