In C++, a function pointer is a pointer that points to a function instead of a variable. It allows you to store the address of a function and invoke it indirectly. This can be useful for scenarios where you need to pass functions as arguments, implement callbacks, or manage a collection of functions dynamically.
Here’s a basic example of how to use function pointers in C++:
Basic Syntax
To declare a function pointer, you specify the return type and the function signature that the pointer will point to. Here’s the general syntax:
return_type (*pointer_name)(parameter_type1, parameter_type2, ...);
Example
Let’s create a simple example to demonstrate how function pointers work.
#include <iostream>
using namespace std;
// A simple function
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int main() {
// Declare a function pointer that points to a function taking two integers and returning an int
int (*operation)(int, int);
// Point to the 'add' function
operation = &add;
cout << "Add: " << operation(5, 3) << endl; // Calls add(5, 3)
// Point to the 'subtract' function
operation = &subtract;
cout << "Subtract: " << operation(5, 3) << endl; // Calls subtract(5, 3)
return 0;
}
Explanation:
- Function Declarations:
- We have two functions:
add
andsubtract
, each accepting two integers and returning an integer.
- We have two functions:
- Function Pointer Declaration:
int (*operation)(int, int);
declares a pointeroperation
that can point to functions that take two integers as arguments and return an integer.
- Assigning Function to Pointer:
operation = &add;
assigns the address of theadd
function to theoperation
pointer.- Later, we change the pointer to point to the
subtract
function.
- Calling the Function Through the Pointer:
operation(5, 3)
calls whichever function the pointer is currently pointing to, and prints the result.
Why Use Function Pointers?
Function pointers are useful in situations like:
- Callback functions: Where you pass a function to be executed later (e.g., in event-driven programming).
- Dynamic function selection: Selecting a function to execute at runtime, such as in a menu-driven program.
- Implementing polymorphism: Using function pointers in structures or classes for method dispatch.
Example with Function Pointer as a Callback
#include <iostream>
using namespace std;
// A simple function to be used as a callback
void greet() {
cout << "Hello, world!" << endl;
}
// A function that accepts a function pointer as an argument
void executeCallback(void (*callback)()) {
callback(); // Calls the function passed as the argument
}
int main() {
// Passing the function pointer 'greet' to 'executeCallback'
executeCallback(greet); // Outputs "Hello, world!"
return 0;
}
In this example, executeCallback
accepts a function pointer callback
and calls it inside the function. This pattern is often used for handling events or customizing behavior.