Function Pointer in C++

Amansingh Javatpoint
2 min readMay 8, 2021

--

A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the address of a function. A function pointer can be used to pass the pointer as a parameter for the other functions and we can call them easily.

Function Address:

We already know that a computer understands only the binary language. In high-level programming languages like C++, a compiler is a program that converts the code into machine understandable and stores it in the executable file. The copy of this executable file is stored in the RAM. When the CPU starts the execution from the main() method, it copies the file from RAM and not the original file.

This process of execution involves occupying some space in the memory. The source code may be a generic one or functional. All these executable source codes occupy space that has an address in RAM. The function pointer has the RAM address of the first instruction of a function.

Syntax:

int (*foo) (int);

OR

int (*FuncPtr) (int,int);

The above syntax is a function declaration. We know that C++ is a type-safe language and the functions are not simple as defining variables. Therefore, function pointers possess a parameter list and return type. In the above syntax, we have defined the return type and the name of the pointer. The function pointer uses the * operator. There are two integers which are the parameters that are passed with them. In simple words, the function pointer FuncPtr can point to any function which has two integer type parameters and a return value of integer type.

Storing function address:

The function pointer stores the address of the function. We do not need to call the function in the driver code, we just need to mention the function name so that we can easily get the address of the function.

--

--

No responses yet