Why operator overloading?
Let’s say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the respective operations. However, to make the code more intuitive and enhance readability, it is preferred to use operators that correspond to the given operations(+, -, *, / respectively) i.e. we can replace the following code
Replace i5 = divide(add(i1, i2), subtract(i3, i4)) by a simpler code: i5 = (i1 + i2) / (i3 - i4)
Overloading the increment operator
The operator symbol for both prefix(++i) and postfix(i++) are the same. Hence, we need two different function definitions to distinguish between them. This is achieved by passing a dummy int parameter in the postfix version.
Here is the code to demonstrate the same.
Before increment: i = 3 After pre increment: i = 4
Before increment: i = 3 After post increment: i = 3
Overloading the decrement operator
Similarly we can also overload the decrement operator as follows
Before decrement: i = 3 After pre decrement: i = 2
Before decrement: i = 3 After post decrement: i = 3
Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.
- Operator Overloading '<<' and '>>' operator in a linked list class
- Difference between Increment and Decrement Operators
- Pre-increment (or pre-decrement) in C++
- Increment (Decrement) operators require L-value Expression
- Pre-increment and Post-increment in C/C++
- Overloading New and Delete operator in c++
- Rules for operator overloading
- Operator Overloading in C++
- Overloading Subscript or array index operator  in C++
- C++ Program to concatenate two strings using Operator Overloading
- Operator overloading in C++ to print contents of vector, map, pair, ..
- Types of Operator Overloading in C++
- C++ program to compare two Strings using Operator Overloading
- Count number of Unique Triangles using Operator overloading
- Overloading the Comma Operator
- vector::operator= and vector::operator[ ] in C++ STL
- deque::operator= and deque::operator in C++ STL
- Why overriding both the global new operator and the class-specific operator is not ambiguous?
- 3-way comparison operator (Space Ship Operator) in C++ 20
- Function overloading and return type
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.