Last Updated on May 15, 2024 by Abhishek Sharma
In C++, functions are treated as first-class citizens, which means they can be passed as arguments to other functions, returned from functions, and stored in data structures. Function pointers allow us to store the address of a function and later call that function through the pointer. This feature is particularly useful in scenarios where we need to select and call a function dynamically at runtime.
What is Function Pointer in C++?
A function pointer in C++ is a variable that stores the memory address of a function. In C++, a function is treated like any other variable, and it can be passed as an argument to another function or returned as a value from a function. When a function is passed as an argument to another function, it is referred to as a C++ function pointer.
How to Declare a Function Pointer in C++?
To declare a function pointer in C++, we use the following syntax:
return_type (*pointer_name)(argument_type1, argument_type2, ...);
Example of How to Declare Function Pointer in C++
If we want to declare a C++ function pointer that points to a function that takes two integer arguments and returns an integer, we would use the following syntax:
int (*func_ptr)(int, int);
Here, func_ptr is a pointer to a function that takes two integer arguments and returns an integer. We can use this pointer to call the function at runtime.
How to Assign a C++ Function Pointer to a Function?
Once we have declared a function pointer, we can assign it to a function using the following syntax.
pointer_name = function_name;
Example of Assigning C++ Function Pointer to a Function:
If we have a function called addNumbers that takes two integer arguments and returns their sum, we can assign its address to a function pointer using the following line of code.
int (*addNumbers_ptr)(int, int) = &addNumbers;
Here, we are assigning the address of the addNumbers function to the addNumbers_ptr pointer. Now, we can use this pointer to call the addNumbers to function at runtime.
How to Call a Function Using a Function Pointer in C++?
To call a function using a function pointer in C++, we use the following syntax:
(*pointer_name)(argument1, argument2, ...);
Example:
If we want to call the addNumbers function using the addNumbers_ptr pointer, we will use the following line.
int result = (*addNumbers_ptr)(2, 3);
Here, we are calling the addNumbers function using the addNumbers_ptr pointer and passing two integer arguments. The result variable will store the sum of these two integers.
Examples of Function Pointer in C++
Now let us understand the Function Pointer in C++ with the help of the following examples.
Example 1 of C++ Function Pointer
Using a function pointer in C++ to pass a function as an argument to another function.
Code:
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } // Function that accepts a function pointer as an argument void operate(int (*operation)(int, int), int x, int y) { int result = (*operation)(x, y); cout << "Result: " << result << endl; } int main() { // Declare a function pointer int (*add_ptr)(int, int) = &add; operate(add_ptr, 2, 3); return 0; }
Output:
Result: 5
Explanation:
In this example, we have defined a function called add that takes two integer arguments and returns their sum. We have also defined a function called operate that accepts a function pointer as an argument and calls it with two integer arguments. In the main function, we have declared a function pointer in C++ called add_ptr that points to the add function. We then call the operate function and pass the add_ptr function pointer as an argument, along with two integer arguments. The operate function calls the function pointed to by the function pointer with the two integer arguments and prints the result to the console. I.e., “Result: 5”.
Example 2 of C++ Function Pointer
Using a function pointer to return a function from another function
Code:
#include <iostream> using namespace std; int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } int divide(int a, int b) { return a / b; } // Function that returns a function pointer int (*get_operation(char op))(int, int) { switch (op) { case '+': return &add; case '-': return &subtract; case '*': return &multiply; case '/': return ÷ default: return NULL; } } int main() { int (*operation)(int, int) = get_operation('+'); int result = (*operation)(2, 7); cout << "Result: " << result << endl; return 0; }
Output:
Result: 9
Explanation:
In this example,
- We have defined a function called “get_operation” that takes a character as an argument and returns a function pointer to the corresponding arithmetic operation function (i.e.,
add
,subtract
,multiply
, ordivide
). - We have also defined four functions to perform basic arithmetic operations.
- In the
main
function, we declare a function pointer calledoperation
and call theget_operation
function to assign it to theadd
function. - We then call the function pointed to by the function pointer with two integer arguments and print the result to the console.
- The
get_operation
function uses a switch statement to determine which arithmetic operation function to return based on the input character, and returnsNULL
if an invalid character is passed as an argument.
Finally, we get output as “Result: 9” on the screen as we passed the 2 and 7 as parameters.
Conclusion
Function pointers in C++ provide a powerful mechanism for working with functions in a flexible and dynamic way. They allow us to write more generic and reusable code by decoupling the function’s address from its call site. While they can be complex to use, especially for beginners, mastering function pointers can greatly enhance your ability to write efficient and flexible code.
Frequently Asked Questions(FAQs) Related to Function Pointer in C++
Here are some Frequently Asked Questions related to “Function Pointer in C++”.
1. Can function pointers point to member functions of a class?
Yes, function pointers can point to both static and non-static member functions of a class. However, there are some differences in how you declare and use them compared to regular function pointers.
2. How do you declare a function pointer in C++?
To declare a function pointer, you specify the return type and parameter types of the function that the pointer will point to, followed by (name) and the function pointer’s name. For example: void (ptr)(int, int); declares a function pointer that can point to a function taking two integers as arguments and returning void.
3. Can you have an array of function pointers in C++?
Yes, you can have an array of function pointers. For example, void (*funcArray[5])(int); declares an array of 5 function pointers, each of which can point to a function taking an integer argument and returning void.
4. What is the use of std::function in C++?
std::function is a more flexible and type-safe alternative to function pointers in C++. It can hold any callable object, including function pointers, lambda functions, and function objects (objects with overloaded operator()). It provides a more object-oriented approach to function handling compared to raw function pointers.
5. How do you call a function through a function pointer?
To call a function through a function pointer, you use the dereference operator followed by the function pointer name, followed by the argument list in parentheses. For example, if ptr is a function pointer, you would call the function it points to like this: (ptr)(arg1, arg2);.