- 2073 Shrawan · 6 marks
Time class: add two objects
Short answer
Define a Time class with hours, minutes, seconds. The add(Time) method sums two times, with carry of 60 seconds to minutes and 60 minutes to hours, returning a new Time object. Example: 2h 45m 50s + 1h 20m 30s = 4h 6m 20s.
Write a program to create class "time" with data members hours, minute and second. Then add two "time" objects by taking object as argument and also returning object as argument.
The class Time has data members hours, minutes and seconds. The function add() receives one Time object as an argument, is called by another object, and returns a new Time object as the result. Seconds and minutes above 59 are carried over.
#include <iostream>
using namespace std;
class Time {
int hours, minutes, seconds;
public:
void getTime() {
cout << "Enter hours, minutes, seconds: ";
cin >> hours >> minutes >> seconds;
}
Time add(Time t2) { // object as argument, object returned
Time t3;
t3.seconds = seconds + t2.seconds;
t3.minutes = minutes + t2.minutes + t3.seconds / 60;
t3.seconds = t3.seconds % 60;
t3.hours = hours + t2.hours + t3.minutes / 60;
t3.minutes = t3.minutes % 60;
return t3;
}
void display() {
cout << hours << " hr " << minutes << " min "
<< seconds << " sec" << endl;
}
};
int main() {
Time t1, t2, t3;
t1.getTime();
t2.getTime();
t3 = t1.add(t2); // t1 calls add, t2 is passed
cout << "Sum = ";
t3.display();
return 0;
}
Sample run
Enter hours, minutes, seconds: 2 45 50
Enter hours, minutes, seconds: 1 20 30
Sum = 4 hr 6 min 20 sec
Check: seconds 50 + 30 = 80, so 20 s with carry 1; minutes 45 + 20 + 1 = 66, so 6 min with carry 1; hours 2 + 1 + 1 = 4.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Vector class addition by object argument · Object Oriented Programming, chapter 1
- Add objects of two different classes · Object Oriented Programming, chapter 4 · asked 2×
- Default argument and overloading program · Object Oriented Programming, chapter 3
- Exception with argument and specification program · Object Oriented Programming, chapter 10
- Abstract Student class program · Object Oriented Programming, chapter 7
- LandMeasure class and sum function · Object Oriented Programming, chapter 4
- Create classes from design class diagrams · Object Oriented Analysis and Design, chapter 4 · asked 2×
- 8085 ALP: add two tables, sum and carry · Microprocessor, chapter 2
- Paired test: safety program worker hours · Probability and Statistics, chapter 6 · asked 3×
- Add two matrices · Computer Programming, chapter 7