Facebook Page Twitter Page LinkedIn Page
× C++ Tutorial C++ Advanced C++ Resources


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 below example, 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 below example, 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