Open In App

How to Overload the Arrow Operator (->) in C++?

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to show how to Overload the Arrow Operator
#include <iostream>
using namespace std;
  
class MyClass {
public:
    int data;
  
    MyClass(int value) : data(value){}
  
    // Overloading the arrow operator
    MyClass* operator->()
    {
        // Returning a pointer to the object
        // itself
        return this;
    }
};
  
int main()
{
    MyClass obj(42);
  
    // Accessing the member 'data' using the arrow operator
    cout << "Using arrow operator: " << obj->data << endl;
  
    // Equivalent to the above, just demonstrating the
    // overloaded arrow operator
    cout << "Direct access: " << obj.data << endl;
  
    return 0;
}


Output

Using arrow operator: 42
Direct access: 42

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads