Class Member Access Operator Overloading in C++

Class Member Access Operator Overloading in C++

What is class member access operator overloading in C++?

Class member access operator or member access operator is denoted by “->”. Classes are given pointer like behavior using member access operator. In this article we will learn more about class member access operator overloading in C++.

Class member access operator overloading in C++

  • It is used to implement “smart pointers.”
  • Its  should return  pointer or an object of a class.
  • The operator is generally used with pointer dereference operator which makes this combination a smart pointer.
  • The derefencing pointer can be defined as a unary postfix operator.

Syntax to overload member access operator in C++

class class_name
{
   obj* operator->();
};

Program showing class member access operator overloading in C++

Run
#include <iostream>
#include <vector>
using namespace std;

class Naruto {
   static int i, j;
   
public:
   void f() const { cout << i++ << endl; }
   void g() const { cout << j++ << endl; }
};

//Defining static member.
int Naruto::i = 1;
int Naruto::j = 2;

//Implementing a container for the above class.
class NarutoContainer {
   vector<Naruto*> a;

   public:
      void add(Naruto* naruto) { 
         a.push_back(naruto); 
      }
      friend class SmartPointer;
};

//Implementing smart pointer to access member of Naruto class.
class SmartPointer {
   NarutoContainer oc;
   int index;
   
   public:
      SmartPointer(NarutoContainer& narutoc) { 
         oc = narutoc;
         index = 0;
      }
   
      // Returnig value indicates end of list.
      bool operator++() { 
         if(index >= oc.a.size()) return false;
         if(oc.a[++index] == 0) return false;
         return true;
      }
   
      bool operator++(int) { 
         return operator++();
      }
   
      //Overloading class member access operator->
      Naruto* operator->() const {
         if(!oc.a[index]) {
            return (Naruto*)0;
         }
      
         return oc.a[index];
      }
};

int main() {
   const int sz = 5;
   Naruto o[sz];
   NarutoContainer oc;
   
   for(int i = 0; i < sz; i++) { oc.add(&o[i]); } SmartPointer sp(oc); do { sp->f(); //Smart pointer call.
      sp->g();
   } while(sp++);
   
   return 0;
}

Output:

1
2
2
3
3
4
4
5
5
6
6
7

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription