C++ Pointer to Function

In This tutorial chapter we will understand and learn the concept of function pointer in C++ and its usage. To properly understand this concept make sure you already know the concept of Pointers in C++. In general Pointers are variables that store address of other variables.

C++ Function Pointer

A function pointer is a type of pointer that stores address of a function. This essentially means that the function pointer points to the body of a function and can be used to call a function.

Function pointers can be useful when you want to create callback mechanism, and need to pass address of an function to another function.
They can also be useful when you want to store an array of functions, to call dynamically.

Lets see an example of function pointer to understand its working:

Run Online

Output
Enter Value of 2-D array A:
Values of A: 10
Program Explanation:

In the above program we have a normal function named fun(int a) with a void return type and one integer argument

In the main function the first line defines a function pointer and assigns the fun function address to this pointer.

  • void – because return type of the actual function is void
  • fun_ptr – name of the function pointer and * to denote that it is a pointer variable
  • &fun – address of the function named fun which is assigned to the function pointer using the assignment operator.

The reason for enclosing the *fun_ptr inside round brackets() is due to the concept of operator precedence. If we don’t use the round brackets and write it as :  void *fun_ptr(int) = &fun then it will mean – a function fun_ptr with one argument of int type and return value of int * i.e. integer pointer.

Following are some interesting facts about function pointers.

  • Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the start of executable code.
  • Unlike normal pointers, we do not allocate de-allocate memory using function pointers.
  • A function’s name can also be used to get functions’ address.
  • Many object oriented features in C++ are implemented using function pointers in C++. For example virtual functions. Class methods are another example implemented using function pointers.
  • Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a function.
    For example, consider the following C++ program given below.

C++ program to show function pointers as parameter

Run Online

Output
Enter Value of 2-D array A:
Function 1
Function 2

Leave a Reply

Your email address will not be published. Required fields are marked *