Increment ++ and Decrement -- Operator Overloading in C++

C++Server Side ProgrammingProgramming

The increment (++) and decrement (--) operators area unit 2 necessary unary operators available in C++. Following example explain how increment (++) operator can be overloaded for prefix as well as postfix usage. Similar way, you can overload operator (--).

Example

#include <iostream>
using namespace std;

class Time {
   private:
   int hours;
   int minutes;

   public:
   Time(int h, int m) {
      hours = h;
      minutes = m;
   }

   void display() {
      cout << "H: " << hours << " M:" << minutes <<endl;
   }

   // overload prefix ++ operator
   Time operator++ () {
      ++minutes;          // increment current object
   if(minutes >= 60) {
      ++hours;
      minutes -= 60;
   }
   return Time(hours, minutes);
}

// overload postfix ++ operator
Time operator++( int ) {
   Time T(hours, minutes);

   // increment current object
   ++minutes;                    

   if(minutes >= 60) {
      ++hours;
      minutes -= 60;
   }        

   // return old original value
   return T;
   }
};
                   
int main() {
   Time T1(11, 59), T2(10,40);

   ++T1;
   T1.display();
   ++T1;
   T1.display();

   T2++;
   T2.display();
   T2++;
   T2.display();
   return 0;
}

Output

This gives the result −

H: 12 M:0
H: 12 M:1
H: 10 M:41
H: 10 M:42
raja
Published on 15-Feb-2018 17:29:45
Advertisements