Designing Reusable Code  «Prev  Next»
Lesson 8 Overloading unary operators
Objective Add postfix decrement/increment operator to clock class.
Examine overloading a unary operator.
For this purpose, we develop the class clock, which is used to store time as days, hours, minutes, and seconds.
This class overloads the prefix autoincrement operator. This overloaded operator is a member function and can be invoked on its implicit single argument.
The member function tick() adds one second to the implicit argument of the overloaded ++ operator.
class clock {
  clock(unsigned long i);   //conversion
  void  print() const;      //format printout
  void  tick();             //add one second
  clock  operator++()
     this -> tick();
  unsigned long  tot_secs, secs, mins, hours, days;

The clock constructor
Now let us look at the constructor for clock. The constructor performs the usual conversions from tot_secs to days, hours, minutes, and seconds. For example, there are 86,400 seconds in a day, therefore; integer division by this constant gives the whole number of days.
inline clock::clock(unsigned long i){
   tot_secs = i;
   secs = tot_secs % 60;
   mins = (tot_secs / 60) % 60;
   hours = (tot_secs / 3600) % 24;
   days = tot_secs / 86400;

The tick() function
The member function tick() constructs clock temp, which adds one second to the total time. The constructor acts as a conversion function that properly updates the time. In addition, tick() uses the overloaded prefix autoincrement operator
void clock::tick(){
  clock  temp = clock(++tot_secs);
  secs = temp.secs;
  mins = temp.mins;
  hours = temp.hours;
  days = temp.days;
Overloaded Unary Operators - Exercise
Click the Exercise link below to try your hand at adding overloaded postfix decrement and increment operators to the clock class.
Overloaded Unary Operators - Exercise