Home CPP Examples Prefix ++ Increment Operator Overloading with no return type

Prefix ++ Increment Operator Overloading with no return type

by anupmaurya
2 minutes read

In this example ,We are going to create a program to Prefix Increment a number using Operator Overloading with no return type

#include <iostream>
using namespace std;

class Check
{
    private:
       int i;
    public:
       Check(): i(0) {  }
       void operator ++() 
          { ++i; }
       void Display() 
          { cout << "i=" << i << endl; }
};

int main()
{
    Check obj;

    // Displays the value of data member i for object obj
    obj.Display();

    // Invokes operator function void operator ++( )
    ++obj; 
  
    // Displays the value of data member i for object obj
    obj.Display();

    return 0;
}

Output

i=0
i=1

Initially when the object obj is declared, the value of data member i for object obj is 0 (constructor initializes i to 0).

When ++ operator is operated on obj, operator function void operator++( ) is invoked which increases the value of data member i to 1.

This program is not complete in the sense that, you cannot used code:

obj1 = ++obj;

It is because the return type of operator function in above program is void.

Here is the little modification of above program so that you can use code obj1 = ++obj.

You may also like

Adblock Detected

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