×

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

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

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.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 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.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

C++ Global Variable

In C++, a global variable is a variable that is defined outside of any function or class and can be accessed by any function or class in the program. Global...

4 minutes read.

Inheritance and Friendship in C++

In this tutorial, we will look into what Inheritance and Friendship in C++ are, as well as the differences between the two. What is Inheritance in C++: In C++, inheritance is an...

2 minutes read.

sort() function in C++

This tutorial covers the various built-in sort functions found in the C++ algorithm’s library.  What Does C++ Sort Mean? The concept of sorting in C++ entails rearranging an array's elements in a...

3 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.