Example The Time Class
Example The Time Class
Let's write a class called Time, which models a specific instance of time with hour, minute and second
values, as shown in the class diagram.
The class Time contains the following members:
Three private data members: hour (0-23), minute (0-59) and second (0-59), with default values
of 0.
A public constructor Time(), which initializes the data members hour, minute and second with
the values provided by the caller.
public getters and setters for private data
members: getHour(), getMinute(), getSecond(), setHour(), setMinute(), and setSecond().
A public member function setTime() to set the values of hour, minute and second given by the
caller.
A public member function print() to print this Time instance in the format "hh:mm:ss", zero-
filled, e.g., 01:30:04.
A public member function nextSecond(), which increase this instance by one
second. nextSecond() of 23:59:59 shall be 00:00:00.
Let's write the code for the Time class, with the header and implementation separated in two
files: Time.h and Time.cpp.
Take note that we have not included input validation (e.g., hour shall be between 0 and 23) in the
constructor (and setters). We shall do that in the later example.
int Time::getHour() const {
return hour;
}
the public getter for private data member hour simply returns the value of the data member hour.
void Time::setHour(int h) {
hour = h;
}
the public setter for private data member hour sets the data member hour to the given value h. Again,
there is no input validation for h (shall be between 0 to 23).
The data members in the initializer list are initialized in the order of their declarations in the class
declaration, not the order in the initializer list.
Test Driver - TestTime.cpp
1 /* Test Driver for the Time class (TestTime.cpp) */
2 #include <iostream>
3 #include "Time.h" // include header of Time class
4 using namespace std;
5
6 int main() {
7 Time t1(23, 59, 59); // Test constructor
8
9 // Test all public member functions
10 t1.print(); // 23:59:59
11 t1.setHour(12);
12 t1.setMinute(30);
13 t1.setSecond(15);
14 t1.print(); // 12:30:15
15 cout << "Hour is " << t1.getHour() << endl;
16 cout << "Minute is " << t1.getMinute() << endl;
17 cout << "Second is " << t1.getSecond() << endl;
18
19 Time t2; // Test constructor with default values for hour, minute and
20 second
21 t2.print(); // 00:00:00
22 t2.setTime(1, 2, 3);
23 t2.print(); // 01:02:03
24
25 Time t3(12); // Use default values for minute and second
26 t3.print(); // 12:00:00
27
28 // Test nextSecond()
29 Time t4(23, 59, 58);
30 t4.print();