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

Function Pointer to Member Function in C++

Last Updated : 28 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, function pointers enable users to treat functions as objects. They provide a way to pass functions as arguments to other functions. A function pointer to a member function is a pointer that points to a non-static member function of a class. In this article, we will learn how to use a function pointer to a member function in C++.

Function Pointer to Member Function in C++

In C++, functions can be treated as objects with the help of function pointers. A function pointer to a member function is a pointer that can refer to a member function of a specific class. Member functions differ from regular functions because they are associated with an instance of a class, which means they have an implicit this pointer that points to the object invoking the object. Following is the syntax to declare a function pointer to a member function:

Syntax

return_type (ClassName::*pointer_name)(argument_types) = &ClassName::member_function;

where:

  • return_type: is the return type of the member function of the class.
  • ClassName: is the name of the class to which the member function belongs.
  • *pointer_name: is the name of the function pointer variable.
  • argument_types: are the types of the arguments accepted by the member function.
  • &ClassName::member_function: is the address of the member function being assigned to the function pointer.

C++ Program to Declare a Function Pointer to Member Function

The below example demonstrates how we can declare a function pointer to a member function in C++:

C++
// C++ Program to Declare a Function Pointer to Member
// Function
#include <iostream>
using namespace std;

class MyClass {
public:
    int value;

    // Constructor to initialize the member variable 'value'
    MyClass(int val)
        : value(val)
    {
    }

    // Member function to add two integers and return the
    // result
    int add(int x, int y) { return x + y; }
};

int main()
{
    // Create an instance of MyClass with the initial value
    // of 10
    MyClass obj(10);

    // Declare a pointer to the member function 'add' of
    // MyClass
    int (MyClass::*ptrToMemberFunc)(int, int)
        = &MyClass::add;

    // Call the member function 'add' using the function
    // pointer

    int result = (obj.*ptrToMemberFunc)(20, 30);

    // Print the result of the function call
    cout << "Result from the member function: " << result
         << endl;

    return 0;
}

Output
Result from the member function: 50

Time Complexity: O(1)
Auxiliary Space: O(1)

Explanation

  • In the above example, we have defined a class MyClass with a member function add that takes two integers and returns their sum.We have then declared function pointer ptrToMemberFunc that points to the member function add.
  • To call the member function using the function pointer, we have used the syntax (obj.*ptrToMemberFunc)(20, 30) where obj is the instance of the class and *ptrToMemberFunc dereferences the function pointer to call the member function with the arguments 20 and 30 of type int.


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 = & 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<stdio.h> int main() { int arr[5] = { 1, 2, 3, 4, 5 }; int *ptr = arr; printf("%p\n", 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
Count the number of objects using Static member function
Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun
2 min read
Calling a non-member function inside a class in C++
Member Function: It is a function that can be declared as members of a class. It is usually declared inside the class definition and works on data members of the same class. It can have access to private, public, and protected data members of the same class. This function is declared as shown below: C/C++ Code // Given Class class memberdemo { priv
3 min read
Static Member Function in C++
The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with the objects of the class. Just like a static variab
4 min read
Can We Access Private Data Members of a Class without using a Member or a Friend Function in C++?
The idea of Encapsulation is to bundle data and methods (that work on the data) together and restrict access of private data members outside the class. In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers. Altho
3 min read
How to Check if a Template Class has the Given Member Function in C++?
In C++ programming, we often need to check if a template class contains a specific member function. In this article, we will discuss how to check if a Template Class has the given member function or not. Check for the Member Function in a Template ClassWe can check whether a member function exists in the template class or not by using SFINAE along
3 min read
How to Declare a Static Member Function in a Class in C++?
In C++, static functions are functions that are directly associated with a class so we can access the static function directly without creating an object of the class using the scope resolution operator. In this article, we will learn how we can declare a static function in a class in C++. Declare a Static Function in a Class in C++To declare a sta
1 min read
How to Sort using Member Function as Comparator in C++?
In C++, sorting is a common operation that can be customized by providing a comparator function. When working with classes, we might need to sort objects based on their member variables. Using a member function as a comparator is a good technique to achieve this. In this article, we will learn how to sort using a member function as a comparator in
3 min read
Can C++ reference member be declared without being initialized with declaration?
To many readers, this might sound the same thing, i.e. class_type *var = NULL; *var = &some_work; is same as class_type *var = &some_work; But in actual, it is not. When the declaration and initialization are done at the same step, the compiler calls the copy constructor whereas if done in another step, the compiler calls the default constr
2 min read
Using Non-Member Friend Functions With Vector in C++ STL
In C++, Non-member buddy functions may access a class's private members while not being members. The class definition declares them friend. Vector containers, dynamic arrays in C++ Standard Library (STL), may dynamically resize as members are added or deleted. You may need to establish a new class with a vector to utilize non-member friend methods
2 min read
Some interesting facts about static member functions in C++
1) static member functions do not have this pointer. For example following program fails in compilation with error "`this' is unavailable for static member functions " C/C++ Code #include<iostream> class Test { static Test * fun() { return this; // compiler error } }; int main() { getchar(); return 0; } 2) A static member function cannot be v
1 min read
Const member functions in C++
Constant member functions are those functions that are denied permission to change the values of the data members of their class. To make a member function constant, the keyword const is appended to the function prototype and also to the function definition header. Like member functions and member function arguments, the objects of a class can also
6 min read
How to Declare a Static Data Member in a Class in C++?
In C++, when we declare a member as static, then it means that the member will have only one copy that is shared by all objects of that class and we don't need any object to access that member In this article, we will learn how to declare a static data member in a class in C++. Declaring Static Data Member in a Class in C++To declare a static membe
2 min read
How to Define a Static Data Member of Type const std::string?
In C++, static data members are members that exist independently of any object of the class. A static data member is shared by all objects of the class, meaning there is only one copy of the static member that is shared by all the objects of the class. In this article, we will learn how to define a static data member of type const std::string in C+
2 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 <iostream> using namespace std; // Pass by reference void swap(int& x, int
3 min read
Function Pointer in C++
Prerequisites: Pointers in C++Function in C++ 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 wi
4 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 Pass an Array Pointer as a Function Argument in C++?
In C++, a common situation arises where we have to pass an array to a function to perform some processing. This can be done by passing an array pointer as a function argument. In this article, we will learn how to pass an array pointer as a function argument in C++. Passing Array Pointer to Function in C++For passing an array to a function, we can
2 min read
How to Create a Pointer to a Function in C++?
In C++, a function pointer is a variable that stores the address of a function that can later be called through that function pointer. It is useful for passing functions as parameters to other functions(callback functions) or storing them in data structures. In this article, we will learn how to use a pointer to a function in C++. Pointer to a Func
2 min read
How to Return a Pointer from a Function in C++?
In C++, we can return a pointer from a function which is useful when we want to return large data structures that cannot be returned by value. However, it must be done carefully to avoid memory leaks, dangling pointers, and other issues related to dynamic memory management. In this article, we will learn how to return a pointer from a function in C
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
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
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", &a);. It might be possible to miss a & and write &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
Passing Reference to a Pointer in C++
Prerequisite: Pointers vs References in C++. For clear understanding, let's compare the usage of a "pointer to pointer" VS "Reference to pointer" in some cases. Note: It is allowed to use "pointer to pointer" in both C and C++, but we can use "Reference to pointer" only in C++. Passing pointer to a function If a pointer is passed to a function as a
4 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
Different ways to use Const with Reference to a Pointer in C++
Before moving forward with using const with Reference to a Pointers, let us first see what they are one by one: Pointers are used to store the address of variables or a memory location. A variable can be declared as a pointer by putting ‘*’ in the declaration. datatype *var_name; Example: // C++ program to // demonstrate a Pointer #include <iost
5 min read
Practice Tags :