The Wayback Machine - https://web.archive.org/web/20240819121311/https://www.geeksforgeeks.org/function-pointer-in-cpp/
Open In App

Function Pointer in C++

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites:

Pointers are symbolic representations of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. Iterating over elements in arrays or other data structures is one of the main use of pointers.

The address of the variable you’re working with is assigned to the pointer variable that points to the same data type (such as an int or string).

Syntax:

datatype *var_name; 

Address of Function: We all know that every function’s code resides in memory, so every function has an address like all other variables in the program. The name of a function can be used to find the address of the function. We can get the address of a function by just writing the function’s name without parentheses in the function.

To know more about this, refer to the article – address of the function.

Function Pointer in C++

  • The function pointer is used to point functions, similarly, the pointers are used to point variables. 
  • It is utilized to save a function’s address. 
  • The function pointer is either used to call the function or it can be sent as an argument to another function.
Function Pointer in C++

Function Pointer in C++

Syntax: 

return_type (*FuncPtr) (parameter type, ....);  

Referencing and Dereferencing of the Function Pointer in C++

Similar to the pointer used with variables we perform referencing and dereferencing with a function pointer.

Referencing: When pointer is allocated the address of the function to be associated with it then this process is referred to as referencing.

Dereferencing: When we use the (*)operator  to get the value stored in the pointer.

Syntax:

// Declaring
return_type (*FuncPtr) (parameter type, ....); 

// Referencing
FuncPtr= function_name;

// Dereferencing
data_type x=*FuncPtr;

Function pointer used to call the function

In this, we see how we point a pointer to a function and call it using that pointer. It is an efficient way to use 

Example:

C++




// C++ program to implementation
// Function Pointer
#include <iostream>
using namespace std;
 
int multiply(int a, int b) { return a * b; }
 
int main()
{
    int (*func)(int, int);
 
    // func is pointing to the multiplyTwoValues function
 
    func = multiply;
 
    int prod = func(15, 2);
    cout << "The value of the product is: " << prod << endl;
 
    return 0;
}


Output

The value of the product is: 30

In the above program, we are declaring a function multiply where we are multiplying two elements a and b, then returning the result. But, rather than directly calling the function we are using a function pointer prod which is doing the same work for us.

Passing a function pointer as a parameter

When declaring a function pointer to store the memory address of the function but, when we want to pass the return value to the next function. We have two methods to perform this task. First, either pass the value we got or second pass the function pointer that already exists.

Example:

C++




// C++ Program for demonstrating
// function pointer as pointer
#include <iostream>
using namespace std;
 
const int a = 15;
const int b = 2;
 
// Function for Multiplication
int multiply() { return a * b; }
 
// Function containing function pointer
// as parameter
void print(int (*funcptr)())
{
    cout << "The value of the product is: " << funcptr()
         << endl;
}
 
// Driver Function
int main()
{
    print(multiply);
    return 0;
}


Output

The value of the product is: 30

Time complexity: O(1).
Auxiliary space: O(1).

In the above program, we are declaring a multiply function in which we multiply 2 variables a and b. We are passing the function pointer as a parameter in the print function, here we use the function pointer to calculate the value from the multiply function and then that value in the print function. 



Previous Article
Next Article

Similar Reads

C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = &amp; normal_variable; What is a Pointer to a Pointer or Double Pointer
4 min read
Pointer to an Array | Array Pointer
Prerequisite: Pointers Introduction  Consider the following program:  [GFGTABS] C #include&lt;stdio.h&gt; int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf(&quot;%p\n&quot;, ptr); return 0; } [/GFGTABS]In the above program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer
9 min read
C++ Function Call By Pointer
Several ways exist in which data (or variables) could be sent as an argument to a function. Two of the common ones are Passing by Value and Passing by Reference. Example: C/C++ Code // C++ Program to demonstrate // Pass by value and // Pass by reference #include &lt;iostream&gt; using namespace std; // Pass by reference void swap(int&amp; x, int
3 min read
Declare a C/C++ function returning pointer to array of integer pointers
Declare "a function with argument of int* which returns pointer to an array of 4 integer pointers". At the first glance it may look complex, we can declare the required function with a series of decomposed statements. 1. We need, a function with argument int *, function(int *) 2. a function with argument int *, returning pointer to (*function(int *
2 min read
How to Specify a Pointer to an Overloaded Function?
In C++, function overloading allows multiple functions to have the same name but different parameter lists. While overloading is a powerful feature, it can lead to ambiguity when trying to assign a pointer to one of these overloaded functions. To resolve this ambiguity, specific methods can be used to correctly specify a pointer to the desired over
4 min read
Pointer vs Array in C
Most of the time, pointer and array accesses can be treated as acting the same, the major exceptions being: 1. the sizeof operator sizeof(array) returns the amount of memory used by all elements in the array sizeof(pointer) only returns the amount of memory used by the pointer variable itself 2. the &amp; operator array is an alias for &amp;array[0
1 min read
Type of 'this' Pointer in C++
In C++, this pointer refers to the current object of the class and passes it as a parameter to another method. 'this pointer' is passed as a hidden argument to all non-static member function calls. Type of 'this' pointer The type of this depends upon function declaration. The type of this pointer is either const ExampleClass * or ExampleClass *. It
2 min read
How to write C functions that modify head pointer of a Linked List?
Consider simple representation (without any dummy node) of Linked List. Functions that operate on such Linked lists can be divided into two categories: 1) Functions that do not modify the head pointer: Examples of such functions include, printing a linked list, updating data members of nodes like adding given a value to all nodes, or some other ope
4 min read
Jump Pointer Algorithm
The Jump pointer algorithm is a design technique for parallel algorithms that operate on pointer structures, such as arrays or linked list. This algorithm is normally used to determine the root of the forest of a rooted tree. In the jump pointer algorithm, we pre-process a tree so that one can able to answer the queries to find any parent of any no
15+ min read
Common Memory/Pointer Related bug in C Programs
Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash whole program. The syntax for scanf() is scanf("%d", &amp;a);. It might be possible to miss a &amp; and write &amp;a as a so now scanf("%d", a); is dereferencing to an unknown location. Now
6 min read
Sum of array using pointer arithmetic
Given an array, write a program to find the sum of array using pointers arithmetic. In this program we make use of * operator . The * (asterisk) operator denotes the value of variable. The * operator at the time of declaration denotes that this is a pointer, otherwise it denotes the value of the memory location pointed by the pointer . sum() functi
2 min read
C++ Program to count Vowels in a string using Pointer
Pre-requisite: Pointers in C++ Given a string of lowercase english alphabets. The task is to count number of vowels present in a string using pointers Examples: Input : str = "geeks" Output : 2 Input : str = "geeksforgeeks" Output : 5 Approach: Initialize the string using a character array. Create a character pointer and initialize it with the firs
2 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
C++ Pointer Operators
Prerequisite: Pointers in C++ A pointer variable is a variable that stores the address of another variable or in other a pointer variable points to the variable whose address is stored inside it. Syntax: int *pointer_name; There are mainly two types of Pointer operators mainly used: Address of operator (&amp;)The indirection operator/Dereference op
2 min read
C++ - Pointer to Structure
Pointer to structure in C++ can also be referred to as Structure Pointer. A structure Pointer in C++ is defined as the pointer which points to the address of the memory block that stores a structure. Below is an example of the same: Syntax: struct name_of_structure *ptr; // Initialization of structure is done as shown below ptr = &amp;structure_var
2 min read
Dereference Pointer in C
We know that the pointer variable can store the memory address in C language and in this article, we will learn how to use that pointer to access the data stored in the memory location pointed by the pointer. What is a Pointer? First of all, we revise what is a pointer. A pointer is a variable that stores the memory address of another variable. The
4 min read
Multidimensional Pointer Arithmetic in C/C++
In C/C++, arrays and pointers have similar semantics, except on type information. As an example, given a 3D array int buffer[5][7][6]; An element at location [2][1][2] can be accessed as "buffer[2][1][2]" or *( *( *(buffer + 2) + 1) + 2). Observe the following declaration T *p; // p is a pointer to an object of type T When a pointer p is pointing t
4 min read
'this' pointer in C++
To understand 'this' pointer, it is important to know how objects look at functions and data members of a class. Each object gets its own copy of the data member. All-access the same function definition as present in the code segment. Meaning each object gets its own copy of data members and all objects share a single copy of member functions. Then
5 min read
Scope Resolution Operator vs this pointer in C++
Scope resolution operator is for accessing static or class members and this pointer is for accessing object members when there is a local variable with the same name. Consider below C++ program: C/C++ Code // C++ program to show that local parameters hide // class members #include &lt;iostream&gt; using namespace std; class Test { int a; public: Te
3 min read
Opaque Pointer in C++
Opaque as the name suggests is something we can't see through. e.g. wood is opaque. An opaque pointer is a pointer that points to a data structure whose contents are not exposed at the time of its definition. The following pointer is opaque. One can't know the data contained in STest structure by looking at the definition. struct STest* pSTest; It
6 min read
Passing By Pointer vs Passing By Reference in C++
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result. So, what is the difference between Passing by Pointer and Passing by Reference in C++? Let's first understand what Passing by Pointer and Passing by Reference in C++ mean: Passing by Pointer Here, the memory location (address) of
5 min read
A C/C++ Pointer Puzzle
Prerequisite: Pointers Assuming the size of int = 4 bytes, size of a pointer variable = 8 byte, what will be the output of following program. Few hints on how to solve it: Size of int = 4 bytes, size of a pointer variable = 8 bytes (on my machine), adding 1 to a pointer makes the pointer point to its next immediate type a is of type int (*)[5][6] a
2 min read
Delete multiple occurrences of key in Linked list using double pointer
Given a singly linked list, delete all occurrences of a given key in it. For example, consider the following list. Input: 2 -&gt; 2 -&gt; 4 -&gt; 3 -&gt; 2 Key to delete = 2Output: 4 -&gt; 3 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.This is mainly an alternative of this post which deletes multiple occurrence
6 min read
Application of Pointer in C++
A pointer is a variable that stores the memory address as its value. It points to the location in the computer's memory where the actual data is stored. Pointer is one of the core features of the C++ programming language which enables various functions like dynamic memory allocation, pass-by-reference, etc. In this article, we will look at some maj
8 min read
void Pointer in C++
In C++, a void pointer is a pointer that is declared using the 'void' keyword (void*). It is different from regular pointers it is used to point to data of no specified data type. It can point to any type of data so it is also called a "Generic Pointer". Syntax of Void Pointer in C++void* ptr_name; As the type of data the void pointer is pointing t
7 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
Pointer to an Array in C++
Pointers in C++ are variables that store the address of another variable while arrays are the data structure that stores the data in contiguous memory locations. In C++, we can manipulate arrays by using pointers to them. These kinds of pointers that point to the arrays are called array pointers or pointers to arrays. In this article, we will discu
6 min read
NULL Pointer in C++
A NULL Pointer in C++ indicates the absence of a valid memory address in C++. It tells that the pointer is not pointing to any valid memory location In other words, it has the value "NULL" (or 'nullptr' since C++11). This is generally done at the time of variable declaration to check whether the pointer points to some valid memory address or not. I
4 min read
C++ Pointer Arithmetic
In C++, pointer variables are used to store the addresses of other variables, functions, structures, and even other pointers and we can use these pointers to access and manipulate the data stored at that address. Pointer arithmetic means performing arithmetic operations on pointers. It refers to the operations that are valid to perform on pointers.
8 min read
How to Get std::vector Pointer to Raw Data in C++?
In C++, std::vector is a dynamic array that stores the data in the contiguous memory allocated during runtime. It internally keeps the pointer to this raw data memory. In this article, we will learn how to get std::vector pointer to the raw data. Methods to Get Pointer to Raw Data in std::vectorIn C++, there are two ways to find the pointer to the
3 min read
three90RightbarBannerImg