Function Pointers
In C++, a function pointer is a variable that stores the memory address of a function. It allows you to call functions indirectly using the pointer.
Declaring Function Pointers
To declare a function pointer, you need to specify the return type of the function and the types of its parameters. Here's the syntax:
1return_type (*pointer_name)(parameter_types);
For example, to declare a function pointer that points to a function that takes two int
parameters and returns an int
, you would use the following declaration:
1int (*sumPtr)(int, int);
Assigning Function Addresses to Pointers
To assign a function's address to a function pointer, you can use the &
operator followed by the function's name. For example, to assign the address of a function add
to a function pointer sumPtr
, you would use the following assignment:
1sumPtr = &add;
Calling Functions using Pointers
To call a function using a function pointer, you can use the function call operator ()
. For example, to call the function pointed to by sumPtr
, you would use the following syntax:
1int result = sumPtr(3, 4);
Example
Let's see an example that demonstrates the use of function pointers:
1// Function to add two numbers
2int add(int a, int b) {
3 return a + b;
4}
5
6// Function to subtract two numbers
7int subtract(int a, int b) {
8 return a - b;
9}
10
11int main() {
12 // Declare function pointers
13 int (*sumPtr)(int, int);
14 int (*subPtr)(int, int);
15
16 // Assign function addresses to pointers
17 sumPtr = &add;
18 subPtr = &subtract;
19
20 // Call functions using pointers
21 int sum = sumPtr(4, 5);
22 int difference = subPtr(10, 7);
23
24 // Output results
25 cout << "Sum: " << sum << endl;
26 cout << "Difference: " << difference << endl;
27
28 return 0;
29}
In this example, we declare two functions add
and subtract
that take two int
parameters and return an int
. We then declare two function pointers sumPtr
and subPtr
. We assign the addresses of the add
and subtract
functions to the respective function pointers. Finally, we call the functions using the pointers and output the results.
xxxxxxxxxx
}
using namespace std;
// Function to add two numbers
int add(int a, int b) {
return a + b;
}
// Function to subtract two numbers
int subtract(int a, int b) {
return a - b;
}
int main() {
// Declare function pointers
int (*sumPtr)(int, int);
int (*subPtr)(int, int);
// Assign function addresses to pointers
sumPtr = &add;
subPtr = &subtract;
// Call functions using pointers
int sum = sumPtr(4, 5);
int difference = subPtr(10, 7);
// Output results
cout << "Sum: " << sum << endl;