How to Create a Pointer to a Function in C++?
Last Updated :
04 Apr, 2024
In C++, a function pointer is a variable that stores the address of a function that can later be called through that function pointer. It is useful for passing functions as parameters to other functions(callback functions) or storing them in data structures. In this article, we will learn how to use a pointer to a function in C++.
Pointer to a Function in C++
A pointer to a function is declared by specifying the function’s return type, followed by an asterisk (*) inside parenthesis
, the pointer name, and the parameter types of the function in parentheses.
Declaring a Pointer to a Function in C++
return_type(*pointer_name)(parameter_list)
Here,
- return_type denotes the type of value returned by the function.
- pointer_name denotes the name of the pointer to a function.
- parameter_list denotes the list of parameters the function can accept.
The parenthesis around the pointer_name is necessary, otherwise, it will be treated as a function declaration with the return type of return_type* and name pointer_name;
Initializing a Pointer to a Function in C++
We can initialize a pointer to a function by assigning it the address of a function with a matching signature.
pointer_name = function_name; // Or &function_name
Here, function_name
is the name of the function the pointer is associated with.
Note: The address-of operator (&)
is optional when initializing function pointers because the function name decays to a pointer to the function.
C++ Program to Create a Pointer to a Function
The following program illustrates how we can create and use a pointer to a function in C++.
C++
// C++ Program to illustrate how we can create and use a
// pointer to a function
#include <iostream>
using namespace std;
// A simple function to be pointed to
void display()
{
cout << "Hello Geek, Welcome to gfg!" << endl;
}
int main()
{
// Declare a function pointer
void (*func_ptr)();
// Point it to the 'display' function
func_ptr = display;
// Call the function through the function pointer
(*func_ptr)();
return 0;
}
OutputHello Geek, Welcome to gfg!
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...