Operator Overloading of Decrement — Operator

241 views

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; }
Code language: PHP (php)

Output

i = 3 i = 3 i = 2 i = 2 i = 1 i = 2
Code language: C++ (cpp)

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

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Enable Notifications    OK No thanks