Increment and Decrement Example using Operator Overloading in C++


The code defines a class called Time which represents a time in hours and minutes. It has a constructor, a method to display the time, and two overloaded operators: ++ (prefix) and ++ (postfix). The prefix ++ operator increments the time by 1 minute and returns the updated time. If the minutes exceed 60, it increments the hours and adjusts the minutes accordingly.

The postfix ++ operator also increments the time by 1 minute but returns the original time (before incrementing). It then performs the same check for adjusting the hours and minutes. In the main function, two Time objects (T1 and T2) are created with initial values. The prefix ++ operator is called twice on T1, and the postfix ++ operator is called twice on T2. The displayTime method is used to print the updated times.

Source Code

#include<iostream>
using namespace std;
class Time
{
   private:
      int hours;
      int minutes;
   public:
      Time()
      {
        hours=0;
        minutes=0;
      }
      Time(int h,int m)
      {
        hours=h;
        minutes=m;
      }
      void displayTime()
      {
        cout<<"H: "<<hours<<" M:"<<minutes<<endl;
      }
      Time operator++ ()
      {
        ++minutes;
        if(minutes>=60)
        {
          ++hours;
          minutes-=60;
        }
        return Time(hours,minutes);
      }
      Time operator++(int)
      {
        Time T(hours,minutes);
        ++minutes;
        if(minutes>=60)
        {
          ++hours;
          minutes-=60;
        }
        return T;
      }
};
int main()
{
  Time T1(11, 59), T2(10,40);
  ++T1;
  T1.displayTime();
  ++T1;
  T1.displayTime();
  T2++;
  T2.displayTime();
  T2++;
  T2.displayTime();
  return 0;
}
To download raw file Click Here

Output

H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples