Function Pointer to Member Function in C++
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++ 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.