Prefix Increment ++ operator overloading with return type

by anupmaurya
0 comment 501 views

#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(0) { } // Return type is Check Check operator ++() { Check temp; ++i; temp.i = i; return temp; } void Display() { cout << "i = " << i << endl; } }; int main() { Check obj, obj1; obj.Display(); obj1.Display(); obj1 = ++obj; obj.Display(); obj1.Display(); return 0; }
Code language: PHP (php)


i = 0 i = 0 i = 1 i = 1

This program is similar to the one above.

The only difference is that, the return type of operator function is Check in this case which allows to use both codes ++obj; obj1 = ++obj;. It is because, temp returned from operator function is stored in object obj.

Since, the return type of operator function is Check, you can also assign the value of obj to another object.

Notice that, = (assignment operator) does not need to be overloaded because this operator is already overloaded in C++ library.

You may also like