- In C++, we can make operators to work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.
- In this article, we will overload an operator ‘+’ in the Time class so that we can concatenate two timestamps by just using +.
Example:
Input: T1 = 5:50:30, T2 = 7:20:34
Output: 13:11:4
Approach: To achieve the + operator overloading, below steps/functions are made:
Class Time is defined in which there are 3 variables to store the value of hours, minutes and seconds respectively.
int HR, MIN, SEC; where HR is for hours, MIN is for minutes, and SEC is for seconds
- setTime() function to set values of HR, MIN and SEC.
void setTime(int x, int y, int z) { x = HR; y = MIN; z = SEC; }
- showTime() function to display the time in a specific format (HH:MM:SS).
void showTime() { cout << HR << ":" << MIN << ":" << SEC; }
- normalize() function to convert the resultant time into standard form.
Overloading of + operator to add time T1 and T2 using operator overloading.
Below is the C++ program implementing + overloading to add two timestamps:
C++
// C++ program to implement + operator // overloading to add two timestamps #include <iostream> using namespace std;
// Time class template class Time {
private :
int HR, MIN, SEC;
// Defining functions
public :
// Functions to set the time
// in the Time class template
void setTime( int x, int y, int z)
{
HR = x;
MIN = y;
SEC = z;
}
// Function to print the time
// in HH:MM:SS format
void showTime()
{
cout << endl
<< HR << ":" << MIN << ":" << SEC;
}
// Function to normalize the resultant
// time in standard form
void normalize()
{
MIN = MIN + SEC / 60;
SEC = SEC % 60;
HR = HR + MIN / 60;
MIN = MIN % 60;
}
// + Operator overloading
// to add the time t1 and t2
Time operator+(Time t)
{
Time temp;
temp.SEC = SEC + t.SEC;
temp.MIN = MIN + t.MIN;
temp.HR = HR + t.HR;
temp.normalize();
return (temp);
}
}; // Driver code int main()
{ Time t1, t2, t3;
t1.setTime(5, 50, 30);
t2.setTime(7, 20, 34);
// Operator overloading
t3 = t1 + t2;
// Printing results
t1.showTime();
t2.showTime();
t3.showTime();
return 0;
} |
Output:
5:50:30 7:20:34 13:11:4