Overloading increment and decrement operators in C++

Overloading ++/- -operators

  • Operator overloading enhances the power of extensibility of c++
  • It provides new meaning to most of the cplusplus operators 
  • As a result, the operator that is overloaded is capable to provide special meaning to the user-defined data types as well.

We can overload unary operators like ++,–etc to directly manipulate the object of a class

Syntax:

return_type::operator increment/decrementoperator _symbol(parameters)
{
// function definition
}

Here  operator is a keyword  increment/decrement operator  symbol is the operator to be overloaded

++/-- overloading

Overloading Prefix increment (++)  operator

#include<iostream>
using namespace std;

class test
{
private:
int i;
public:
test(): i(0) { }//initialise data memeber

void operator ++()
{
++i;
}

void display()
{
cout << "i:" << i << "\t";
}
};

int main()
{
test t;

// Displays the value of data member i for object t
t.display();

// Invoke the  operator function void operator ++( )
++t;

// Displays the value of data member i for object t
t.display();
return 0;
}

O/P

i:0    i:1
  • Initially, when test t is declared, the value of data member i for object test t  is 0 (constructor initializes i to 0).
  • When ++ operator is called  on the object t, operator function void operator++( ) is invoked which increments the value of data member i to 1.