In C++, a function pointer is a specific type of pointer that points to a function rather than a data value. This feature allows functions to be passed as parameters, saved in arrays, or returned from other functions. Such functionality facilitates dynamic function invocations and versatile programming architectures, including callbacks and function tables.
In C++, pointers are utilized to reference variables; likewise, a function pointer is a pointer employed to reference functions. Essentially, it is utilized to hold the memory address of a function. Functions can be invoked through the function pointer, or the pointer can be transferred as an argument to another function. They are particularly beneficial for event-driven software, callbacks, and even for storing functions in arrays.
What is the Address of a Function?
As it is commonly understood, computers solely comprehend the low-level language, specifically in binary format. Within C++, each function within a program is primarily saved in the primary memory (RAM) following compilation. Utilizing the compiler, we can transform the high-level source code into machine code, which is then stored in an executable file. This executable file is then stored in RAM. The CPU initiates execution from the main function and accesses the version stored in RAM rather than the original file.
All functions and machine code instructions are essentially data, consisting of a sequence of bytes with specific addresses in RAM. Function pointers store the RAM address of the initial instruction within a function.
Declaration of Function Pointer
The subsequent syntax demonstrates how a function pointer is declared:
return_type (*Pointer_name) (parameter_list);
In this particular format,
- *Pointer_name: Signifies the identifier of the pointer.
- Parameter_list: Indicates the collection and names of the parameters.
Getting the Address of a Function
In C++, obtaining the memory location of a function is a straightforward process. To retrieve the address of a function, simply reference the function's name without invoking it.
C++ Example of Getting the Address of a Function
Let's consider a scenario to demonstrate how to obtain the memory location of a function in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
cout << "Address of a main() function is : " <<&main<<endl;
return 0;
}
Output:
Address of a main() function is : 1
Explanation:
In the provided code snippet, we are showcasing the memory location of the main function. To showcase the address of the main function, we simply reference the function name without parentheses or arguments. Hence, the function name alone, devoid of parentheses or arguments, signifies the memory address of the function.
Calling the Function Indirectly using the Function Pointer
In C++, invoking a function can be achieved using a function pointer by directly referencing the function pointer's name. The method of invoking a function through a function pointer closely resembles the conventional way of calling a function.
C++ Example to Call the Function Indirectly using the Function Pointer
Let's consider an illustration to demonstrate calling a function indirectly through a function pointer.
Example
#include <iostream>
using namespace std; //using standard namespace
int add(int a , int b)
{
return a+b;
}
int main() //main function
{
int (*funcptr)(int,int); // function pointer declaration
funcptr=add; // funcptr is pointing to the add function
int sum=funcptr(5,5);
cout << "value of sum is : " <<sum<<endl;
return 0;
}
Output:
value of sum is : 10
Explanation:
In this instance, we define the function pointer as int (*funcptr)(int,int), and subsequently assign the address of the add function to funcptr. This means that funcptr now holds the address of the add function. Consequently, we are able to invoke the add function using funcptr. Ultimately, executing the statement funcptr(5, 5) triggers the add function, and the output of add is stored in the sum variable.
Using Function Pointer with a String
In C++, function pointers are not limited to only numerical operations; they can also be employed with any function signature, such as those that accept char* or std::string types. This versatility is particularly valuable for managing string-related tasks like custom printing, parsing, formatting, and more.
C++ Function Pointer with a String Example
Let's consider an illustration to demonstrate the usage of a function pointer with a string in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
void printname(char *name)
{
cout << "Name of the person is : " <<name<<endl;
}
int main() //main function
{
char s[20]; // array declaration
void (*ptr)(char*); // function pointer declaration
ptr=printname;
cout << "Enter the name of the person: ";
cin>>s;
ptr(s); // calling printname() function
return 0;
}
Output:
Enter the name of the person: John
Name of the person is : John
Explanation:
In this instance, we are outlining the printname function which accepts a char pointer as an argument. Subsequently, we establish a function pointer as void (ptr)(char). Assigning the function address of printname to ptr is denoted by the statement ptr=printname. Eventually, invoking the printname function is achieved through the statement ptr(s).
Array of Function Pointers
In C++, a function pointer array is a grouping where each item represents a pointer to a function. This array facilitates the flexible selection of functions and allows for function invocation based on index or certain conditions.
Syntax
It has the following syntax:
return_type (*array_name[])(parameter_list);
C++ Array of Function Pointers Example
Let's consider an example to demonstrate an array of function pointers in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
// Define some functions
int addition(int x, int y) { return x + y; }
int subtract(int x, int y) { return x - y; }
int multiply(int x, int y) { return x * y; }
int main() { //main function
// Declare an array of function pointers
int (*operations[3])(int, int) = {addition, subtract, multiply};
int a = 20, b = 18;
cout << "Addition: " << operations[0](a, b) << endl;
cout << "Subtract: " << operations[1](a, b) << endl;
cout << "Multiply: " << operations[2](a, b) << endl;
return 0;
}
Output:
Addition: 38
Subtract: 2
Multiply: 360
Explanation:
In this instance, a function pointer array named operations is employed to hold three arithmetic functions: addition, subtraction, and multiplication. Each function pointer within the array is invoked with two integer parameters (a and b), enabling flexible execution of the corresponding operations.
Pass a Function Pointer as a Parameter
In C++, a function pointer can be provided as an argument to another function, enabling dynamic functionality. To achieve this, there are two primary approaches. Initially, the value obtained can be passed, or alternatively, an existing function pointer within the program can be passed.
C++ Pass a Function Pointer as a Parameter Example
Let's consider an illustration to demonstrate how to pass a function pointer as an argument in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
void func1()
{
cout<<"func1 is called";
}
void func2(void (*funcptr)())
{
funcptr();
}
int main() //main function
{
func2(func1);
return 0;
}
Output:
func1 is called
Explanation:
In this instance, the func2 function accepts a function pointer as an argument. Subsequently, the main function invokes func2, passing the address of func1. This process enables func2 to indirectly execute func1.
C++ Function Pointer MCQs
1) What is the Function Pointer in C++?
- It is a pointer that stores the address of a class object
- It is a pointer that stores the address of a function
- It is a pointer that stores the address of a variable
- It is a pointer that stores the return value of a function
2) Which of the following options shows the correct syntax of function pointer in C++?
- int *func(int, int);
- int (*funcptr)(int, int);
- int funcptr(int, int);
- int &funcptr(int, int);
3) What will be the output of the following code?
#include <iostream>
using namespace std;
void CppTutorial() { cout << "CppTutorial"; }
void Tech() { cout << "Tech"; }
int main() {
void (*fptr[2])() = {CppTutorial, Tech};
fptr[1]();
return 0;
}
- Tech
- Cpp Tutorial
- CppTutorial
- CppTutorial, Tech
4) Which one of the following option is not a correct use of function pointers in C++?
- Storing in an array
- Passing as an argument to another function
- Calling a constructor
- Returning a function from a function
5) What will be the output of the following code?
#include <iostream>
using namespace std;
void func(int a)
{
cout << a;
}
int main()
{
void (*n)(int);
n = &func;
(*n)( 5 );
n( 5 );
return 0;
}