Overloading increment and decrement operators in C++

Overloading increment and decrement operators in C++

Overloading ++/- – operators

Overloading Operator enhances the power of extensibility of C++.
It provides new meaning to most of the cplusplus operator.

Overloading increment and decrement operators in C++

  • 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 Prefix increment (++)  operator

Run
#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;
}

Output

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.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription