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 member access operator overloading in C++.

But if the term operator overloading is new to you , we would suggest you to read about it by clicking the button below.

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

#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