Postfix Increment ++ Operator Overloading

by anupmaurya
435 views

Overloading of increment operator up to this point is only true if it is used in prefix form.

This is the modification of above program to make this work both for prefix form and postfix form.

#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(0) { } Check operator ++ () { Check temp; temp.i = ++i; return temp; } // Notice int inside barcket which indicates postfix increment. 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 = 0 i = 0 i = 1 i = 1 i = 2 i = 1

When increment operator is overloaded in prefix form; Check operator ++ () is called but, when increment operator is overloaded in postfix form; Check operator ++ (int) is invoked.

Notice, the int inside bracket. This int gives information to the compiler that it is the postfix version of operator.

Don’t confuse this int doesn’t indicate integer.

You may also like