C++ Tutorial C++ Advanced C++ References

C++ - Increment & Decrement Operator Overloading



The increment (++) and decrement (--) are two important unary operators in C++. Each operator has two variant :

  • Pre-increment & Post-increment
  • Pre-decrement & Post-decrement

Example: overloading increment operator

In the example below, increment operator is overloaded. When it is used with vector object, it increases x and y component of the object by 1, for example - applying pre-increment operator on (10, 15) will produce (11, 16) before it is used, and applying post-increment on (10, 15) will produce (11, 16) after it is used.

#include <iostream>
using namespace std;
 
class vector {
  public:
    int x, y;
    vector(){}

    //class constructor
    vector(int x, int y) {
      this->x = x;
      this->y = y;
    }

    //function to display vector
    void displayVector() {
      cout<<"("<<x<<", "<<y<<")\n"; 
    }

    //overloading pre-increment operator
    vector operator++ () {
      x++;
      y++;  
      return *this;    
    }

    //overloading post-increment operator
    vector operator++ (int) {
      vector temp = *this;
      this->x++;
      this->y++;  
      return temp;   
    }    
};
int main (){
  vector v1(10, 15), v2;

  v2 = ++v1;
  v1.displayVector();
  v2.displayVector();

  v2 = v1++;
  v1.displayVector();
  v2.displayVector();

  return 0;
}

The output of the above code will be:

(11, 16)
(11, 16)
(12, 17)
(11, 16)

Example: overloading decrement operator

In the example below, decrement operator is overloaded. When it is used with vector object, it decreases x and y component of the object by 1, for example - applying pre-decrement operator on (10, 15) will produce (9, 14) before it is used, and applying post-decrement on (10, 15) will produce (9, 14) after it is used.

#include <iostream>
using namespace std;
 
class vector {
  public:
    int x, y;
    vector(){}

    //class constructor
    vector(int x, int y) {
      this->x = x;
      this->y = y;
    }

    //function to display vector
    void displayVector() {
      cout<<"("<<x<<", "<<y<<")\n"; 
    }

    //overloading pre-decrement operator
    vector operator-- () {
      x--;
      y--;  
      return *this;    
    }

    //overloading post-decrement operator
    vector operator-- (int) {
      vector temp = *this;
      this->x--;
      this->y--;  
      return temp;   
    }    
};
int main (){
  vector v1(10, 15), v2;

  v2 = --v1;
  v1.displayVector();
  v2.displayVector();

  v2 = v1--;
  v1.displayVector();
  v2.displayVector();

  return 0;
}

The output of the above code will be:

(9, 14)
(9, 14)
(8, 13)
(9, 14)

❮ C++ - Operator Overloading