C++ Pointers Function Pointer
Syntax:
return_type (*pointer_name)(function_arguments)
Example:
#include <iostream>
void printNumber(int num) {
std::cout << "Number: " << num << std::endl;
}
void printChar(char ch) {
std::cout << "Character: " << ch << std::endl;
}
int main() {
void (*printFunction)(int); // Pointer to printNumber function
void (*printFunction2)(char); // Pointer to printChar function
printFunction = &printNumber; // Assigning address of printNumber function to pointer
printFunction(10); // Calling printNumber function using pointer
printFunction2 = &printChar; // Assigning address of printChar function to pointer
printFunction2('a'); // Calling printChar function using pointer
return 0;
}
Output:
Number: 10
Character: a
Explanation:
Function pointers point to functions, allowing you to pass functions as arguments to other functions or to use functions as data in your programs. The syntax for function pointers requires the function's return type, followed by a set of parentheses containing the function's arguments, which is then followed by an asterisk and a variable name.
In the above example, we declare two pointers to two different functions, which we then assign to those functions by taking their address. We then use these pointers to call the functions just like we would with a regular function call.
Use:
Function pointers are useful when you want to pass a function as an argument to another function or you want to return a function from a function. They can also be used to implement callbacks, allowing you to register a function to be called later when a certain event occurs.
Important Points:
- A function pointer is declared by specifying the function's return type, followed by a set of parentheses containing the function's arguments, which is then followed by an asterisk and a variable name.
- You can assign a function to a function pointer by taking the address of the function.
- You can call a function using a function pointer by using the syntax
functionPointerName(argumentList)
.
Summary:
In this tutorial, we learned about function pointers in C++. We saw how to declare, assign, and use them, and we also learned about some use cases for function pointers. By understanding function pointers, you can improve your ability to pass functions around in your programs, making your code more modular and extensible.