Increment Decrement Operators Overloading
# C++ Increment (++) and Decrement (--) Operator Overloading
[ C++ Overloading Operators and Functions](#)
The increment operator (++) and the decrement operator (--) are two important unary operators in the C++ language.
The following example demonstrates how to overload the increment operator (++), including both prefix and postfix usage. Similarly, you can also try overloading the decrement operator (--).
## Example
#includeusing namespace std; class Time{private: int hours; // 0 to 23 int minutes; // 0 to 59 public: // Required constructor Time(){hours = 0; minutes = 0; }Time(int h, int m){hours = h; minutes = m; }// Method to display time void displayTime(){cout<<"H: "<<hours<<" M:"<<minutes<= 60){ ++hours; minutes -= 60; }return Time(hours, minutes); }// Overload postfix increment operator (++) Time operator++(int){// Save original value Time T(hours, minutes); // Increment object by 1 ++minutes; if(minutes>= 60){ ++hours; minutes -= 60; }// Return old original value return T; }}; int main(){Time T1(11, 59), T2(10,40); ++T1; // Increment T1 by 1 T1.displayTime(); // Display T1 ++T1; // Increment T1 by 1 again T1.displayTime(); // Display T1 T2++; // Increment T2 by 1 T2.displayTime(); // Display T2 T2++; // Increment T2 by 1 again T2.displayTime(); // Display T2
YouTip