How to Overload the Arrow Operator (->) in C++?
Last Updated :
27 Feb, 2024
C++ has the ability to redefine the function of operators for the objects of some class. This is called operator overloading. In this article, we will learn how to overload the arrow operator (->) in C++.
Overload the Arrow Operator in C++
To overload the arrow operator for your class, you must define an operator member function in your class with the name operator(->) and define the new behavior of the arrow operator in this function. Whenever the objects of this function are used with (->) arrow operator, the statements inside the operator function will be executed.
Syntax to Overload the Arrow Operator
class sampleClass
{
returntype operator -> ( [arguments required] )
{
//sampleCodeHere
}
};
C++ Program to Overload the Arrow Operator
C++
#include <iostream>
using namespace std;
class MyClass {
public :
int data;
MyClass( int value) : data(value){}
MyClass* operator->()
{
return this ;
}
};
int main()
{
MyClass obj(42);
cout << "Using arrow operator: " << obj->data << endl;
cout << "Direct access: " << obj.data << endl;
return 0;
}
|
Output
Using arrow operator: 42
Direct access: 42
Share your thoughts in the comments
Please Login to comment...