Increment (++) and Decrement (- -) Operator Overloading in C++
In this tutorial, we will learn what is operator overloading and how to overload increment ++ and decrement — operators along with its implementation in C++.
Operator Overloading
Operator overloading gives separate or additional meaning to an operator. We can do this using the keyword operator.
Syntax
return_type operator operator_symbol (arguments) { //body of the function }
Increment ++ and Decrement — Operator Overloading
The increment and decrement operators are of two types. They are prefix and postfix.
Calling the overloaded operators
There are two ways of calling the overloaded operators. One is by directly incrementing or decrementing the object and the other is by calling it like a method using the object. To differentiate between prefix and postfix operation while calling like a method we need to specify an argument of type int.
Implementation in C++
#include<iostream> using namespace std; class Op_overloading { public : int a, b; //Overloading increment ++ operator void operator ++() { cout << "Prefix increment of a" << endl; ++a; } void operator ++(int) { cout << "Postfix increment of a" << endl; a++; } //Overloading decrement -- operator void operator -- () { cout << "Prefix decrement of b" << endl; --b; } void operator -- (int) { cout << "Postfix decrement of b" << endl; b--; } void display() { cout << "a = " << a << endl; cout << "b = " << b << endl; } }; int main() { Op_overloading obj; obj.a = 5; obj.b = 5; //Calling overloaded increment ++ operator ++obj; obj.display(); obj++; obj.display(); obj.operator ++(); obj.display(); obj.operator ++(1); obj.display(); //Calling overloaded decrement -- operator --obj; obj.display(); obj--; obj.display(); obj.operator --(); obj.display(); obj.operator --(1); obj.display(); }
We created an object named obj for the class Op_overloading
. Using this obj we are performing overloading operations.
Output:
Prefix increment of a a = 6 b = 5 Postfix increment of a a = 7 b = 5 Prefix increment of a a = 8 b = 5 Postfix increment of a a = 9 b = 5 Prefix decrement of b a = 9 b = 4 Postfix decrement of b a = 9 b = 3 Prefix decrement of b a = 9 b = 2 Postfix decrement of b a = 9 b = 1
Also read, Operator Overloading in C++
Function Overloading in C++
Leave a Reply