Home CPP Examples Operator Overloading of Decrement — Operator

Operator Overloading of Decrement — Operator

by anupmaurya

Decrement operator can be overloaded in similar way as increment operator.

#include <iostream>
using namespace std;

class Check
{
  private:
    int i;
  public:
    Check(): i(3) {  }
    Check operator -- ()
    {
        Check temp;
        temp.i = --i;
        return temp;
    }

    // Notice int inside barcket which indicates postfix decrement.
    Check operator -- (int)
    {
        Check temp;
        temp.i = i--;
        return temp;
    }

    void Display()
    { cout << "i = "<< i <<endl; }
};

int main()
{
    Check obj, obj1;    
    obj.Display(); 
    obj1.Display();

    // Operator function is called, only then value of obj is assigned to obj1
    obj1 = --obj;
    obj.Display();
    obj1.Display();

    // Assigns value of obj to obj1, only then operator function is called.
    obj1 = obj--;
    obj.Display();
    obj1.Display();

    return 0;
}

Output

i = 3
i = 3
i = 2
i = 2
i = 1
i = 2

Also, unary operators like: !, ~ etc can be overloaded in similar manner.

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.