In this tutorial you will learn about the C++ Program to Demonstrate Increment ++ and Decrement — Operator Overloading and its application with practical example.
In this tutorial, we will learn to create a C++ program that will Demonstrate Increment ++ and Decrement — Operator Overloading in C++ programming.
Prerequisites.
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- Classes and Objects in C++ programming.
What are the operators?
Operators are symbols with special meanings in a programming language. The operators are used between one or more operand.
There are three types of operators on the basis of operands.
- Unary operator.
- Binary operator.
- Ternary operator.
In this program, we will overload the unary operator i.e. “++”,”–“.
C++ Program for Operator overloading:-
In this program, we will Overload increment and decrement operators. We will use the operators to work for user-defined classes. It means we will use the operators with special meaning in the program for a data type.
Program to overload increment operator:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(0) { } // Return type is Check Check operator ++() { Check flag; ++i; flag.i = i; return flag; } void Display() { cout << "i = " << i << endl; } }; int main() { //declaring the for the class to access the functions Check obj, obj1; obj.Display(); obj1.Display(); obj1 = ++obj; obj.Display(); obj1.Display(); return 0; } |
Program to overload decrement operator:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
#include <iostream> using namespace std; class Check { private: int i; public: Check(): i(3) { } Check operator -- () { Check flag; flag.i = --i; return flag; } // overloading the decrement operator. Check operator -- (int) { Check flag; flag.i = i--; return flag; } void Display() { cout << "i = "<< i <<endl; } }; int main() { Check obj, obj1; obj.Display(); obj1.Display(); // Operator function is called, only then value of obj is assigned to obj1 obj1 = --obj; obj.Display(); obj1.Display(); // Assigns value of obj to obj1, only then operator function is called. obj1 = obj--; obj.Display(); obj1.Display(); return 0; } |
Output for increment:-
Output for decrement:-
Overloading the increment operator.