×

Function Pointer in C++

Definition:

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.

Let us now look at some of the ways through which function pointer stores addresses of functions.

Example 1:

 #include<bits/stdc++.h>
 using namespace std;
 int fool()
 {
     return 5;
 }
 int main()
 {
     cout << fool << '\n';
     return 0;
 } 

Output:

Function Pointer in C++

Explanation:

In the above code, we have declared a function named fool() which returns an integer value 5. To understand this, we need to be clear with the compilers. We have 1 as output in the online GCC compiler while in the other compiler the output may look like - 0xfd23d421.This is nothing but an unreadable memory address that is accessed using a function pointer.

Example 2: Indirect function calling

 #include<bits/stdc++.h>
 using namespace std; 
 int multiply(int x , int y) 
 { 
     return x*y; 
 } 
 int main() 
 { 
                 int (*funcptr)(int,int); 
                 funcptr=multiply;
                 int total=funcptr(4,7); 
                 cout << "Value of multiplication is :" <<total<<endl;
   return 0; 
 }  

Output:

Function Pointer in C++

Explanation:

In the above code, we have used a function pointer to point the function multiply which takes two integer parameters x and y, and returns the multiplication. We have defined a function pointer funcptr that points to the function 'multiply'. The function multiply is passed to the funcptr. This is called an indirect function call. Another variable 'total' stores the value of multiplication which is indirectly passed with both the integer parameters.

The result is then printed on the console.

Note: There can be cases where the function is passed with more or fewer arguments. In such cases, the compiler may return 'too few' or 'too many argument' error.

Example 3: Passing function pointer as a parameter.

  #include<bits/stdc++.h>
 using namespace std; 
 void function1() 
 { 
     cout<<"Function1 is being called!"; 
 } 
 void function2(void (*funcptr)()) 
 { 
     funcptr(); 
 } 
 int main() 
 { 
   function2(function1); 
   return 0; 
 } 

Output:

Function Pointer in C++

Explanation:

In the above code, we have defined two functions named 'function1' and 'function2'. The task is to use function is to pass function pointer as a parameter. To do this, we defined a function pointer 'funcptr' in function2 as a parameter and the pointer is called itself inside the function. When function1 is passed as an argument in function2 then the function pointer 'funcptr' points to function1 and executes the code inside it. By this action, function1 is called as a result and is then displayed on the console.

Note: The main() method calls the function2() in which the address of the function1 is passed. The function2 is calling function1 indirectly.

Points to Remember:

  1. The main task of the function pointer is to allow us to pass a function to a variable and store them for later use.
  • A function pointer is used to point to any function with the same signature.
  • Unlike other pointers, the function pointer does not de-allocate memory.
  • Unlike other pointers, the function pointer points to code, not data.


Related Topics

Single Handling in C++

Introduction: Single handling in C++ refers to a technique for processing multiple events or requests with a single function or handler rather than creating separate functions for each task. This allows...

5 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

How to Setup Environment for C++ Programming on Mac

Mac OS X code Installation There are so many environments available for C++. We are going to install jGrasp and Xcode in our mac operating system. Instruction for installation of jGrasp and...

2 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

Reverse function in C++

The function std::reverse() is included in the standard template library of C++. It takes in a beginning and ending iterator, reversing the order. To use the reverse statement, we need...

2 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Differences Between C Structures and C++ Structures

The below table clearly describes the differences between C and C++ programming languages Structures concepts where the core principle concepts like static members, data handling, pointers, access modifiers, the importance...

3 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Types of polymorphism in C++

What is polymorphism in C++ ? Polymorphism literally translates to "multiple forms". This indicates that the same thing behaves differently depending on the context in programming. Polymorphism is a feature of C++...

6 minutes read.