0% found this document useful (0 votes)
184 views

Example The Time Class

The document describes a Time class that models a specific instance of time with hour, minute and second values. It includes: - Private data members for hour, minute and second - Public constructor, getters and setters for the private data members - Methods to set the time, print the time in a formatted string, and increment the time by one second - The class is defined in a Time.h header file and implemented in a Time.cpp file

Uploaded by

hrishipisal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
184 views

Example The Time Class

The document describes a Time class that models a specific instance of time with hour, minute and second values. It includes: - Private data members for hour, minute and second - Public constructor, getters and setters for the private data members - Methods to set the time, print the time in a formatted string, and increment the time by one second - The class is defined in a Time.h header file and implemented in a Time.cpp file

Uploaded by

hrishipisal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

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.

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
Header - Time.h
1 /* Header for the Time class (Time.h) */
2 #ifndef TIME_H // Include this "block" only if TIME_H is NOT defined
3 #define TIME_H // Upon the first inclusion, define TIME_H so that
4 // this header will not get included more than once
5 class Time {
6 private: // private section
7 // private data members
8 int hour; // 0 - 23
9 int minute; // 0 - 59
10 int second; // 0 - 59
11
12 public: // public section
13 // public member function prototypes
14 Time(int h = 0, int m = 0, int s = 0); // Constructor with default values
15 int getHour() const; // public getter for private data member hour
16 void setHour(int h); // public setter for private data member hour
17 int getMinute() const; // public getter for private data member minute
18 void setMinute(int m); // public setter for private data member minute
19 int getSecond() const; // public getter for private data member second
20 void setSecond(int s); // public setter for private data member second
21 void setTime(int h, int m, int s); // set hour, minute and second
22 void print() const; // Print a description of this instance in "hh:mm:ss"
23 void nextSecond(); // Increase this instance by one second
24 }; // need to terminate the class declaration with a semicolon
25
26 #endif // end of "#ifndef" block
Dissecting Time.h
#ifndef TIME_H
#define TIME_H
......
#endif
To prevent an header file from included more than once into a source file (which could result in
compilation error if an entity is declared twice, e.g., int i), we wrap the header codes within a pair
of preprocessor directives #ifndef (if not define) and #endif. The codes within the if-block will only be
included if the identifier TIME_H has not been defined. This is true for the first inclusion, which also
defines the identifier TIME_H (the first directive in body of the if-block). No subsequent inclusion is
possible, since TIME_H has been defined during the first inclusion. By convention, use the
identifier XXX_H (or XXX_H_INCLUDED) for header Xxx.h.
class Time {
private:
......
public:
......
};

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
The header Time.h contains the class declaration for the class Time. It is divided into two
sections: private and public. The private members (data or functions) are accessible by members of
this class only, while public members are visible by all (such as the main() function which is outside the
class). The class declaration must be terminated by a semicolon.
private:
int hour;
int minute;
int second;
public:
......
We declare 3 private data members called hour, minute and second. In C++98/C++03, you are NOT
allow to initialize a data member in the class declaration (except const static int data members). For
example, setting hour = 0 causes a compilation error. Instead, the data members are to be initialized in
the constructor (to be shown later). The newer C++11 allows initialization of data members.
Only member function prototypes are listed in the class declaration. A function prototype consists of the
return-type, function name and parameter types.
Time(int h = 0, int m = 0, int s = 0);
declares the so-called constructor. A constructor is a special function that has the same name as the class.
A constructor has no return type, or implicitly return void. No return statement is allowed inside the
constructor's body. A constructor can only be used during the instance declaration to initialize the data
members of the instance. It cannot be invoked thereafter.
In the function prototypes of the header, we can set the default values of the function's parameters for
any function member using "= default-value". In this case, this constructor can be invoked with 0 to 3
arguments, the omitted trailing arguments will be set to their default values, e.g.,
Time t1(1, 2, 3); // no default used
Time t2(1, 2); // s = 0 (default)
Time t3(1); // m = 0, s = 0 (defaults)
Time t4; // h = 0, m = 0, s = 0 (all defaults) - no empty parentheses ()
The identifiers h, m and s are not needed in the function prototype - you only need to specify the
parameters' types. But they serve as proper documentation, and are strongly recommended.
int getHour() const;
void setHour(int h);
int getHour() const;
void setHour(int h);
int getHour() const;
void setHour(int h);
declare the so-called getter and setter for the private data member hour, minute and second. Since the
data members are private and are not accessible outside the class, public getters and setters are often
provided to read and modify the private data members. By convention, a getter receives nothing (void)
from the caller and returns a value of the type of the data member; a setter receives a value of the type
of the data member and returns void. Setters may validate the input before setting the value of the data
member.
We declare the getter function constant, by placing the keyword const after the function parameter list.
A const member function cannot modify any data member of this object. Getter does not need to
modify any data member.
void setTime(int h, int m, int s);
declares a public member function to set the hour, minute and second of this instance in one call.

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
void print() const;
declares a public member function to print this instance in the format HH:MM:SS, zero-filled,
e.g., 01:56:09. The function print() returns void.
void nextSecond();
declares a public member function to increase this instance by one second. For
example, 23:59:59 becomes 00:00:00. The function nextSecond() returns void.
Implementation - Time.cpp
1 /* Implementation for the Time Class (Time.cpp) */
2 #include <iostream>
3 #include <iomanip>
4 #include "Time.h" // include header of Time class
5 using namespace std;
6
7 // Constructor with default values. No input validation
8 Time::Time(int h, int m, int s) {
9 hour = h;
10 minute = m;
11 second = s;
12 }
13
14 // public getter for private data member hour
15 int Time::getHour() const {
16 return hour;
17 }
18
19 // public setter for private data member hour. No input validation
20 void Time::setHour(int h) {
21 hour = h;
22 }
23
24 // public getter for private data member minute
25 int Time::getMinute() const {
26 return minute;
27 }
28
29 // public setter for private data member minute. No input validation
30 void Time::setMinute(int m) {
31 minute = m;
32 }
33
34 // public getter for private data member second
35 int Time::getSecond() const {
36 return second;
37 }
38
39 // public setter for private data member second. No input validation

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
40 void Time::setSecond(int s) {
41 second = s;
42 }
43
44 // Set hour, minute and second. No input validation
45 void Time::setTime(int h, int m, int s) {
46 hour = h;
47 minute = m;
48 second = s;
49 }
50
51 // Print this Time instance in the format of "hh:mm:ss", zero filled
52 void Time::print() const {
53 cout << setfill('0'); // zero-filled, need <iomanip>, sticky
54 cout << setw(2) << hour // set width to 2 spaces, need <iomanip>, non-
55 sticky
56 << ":" << setw(2) << minute
57 << ":" << setw(2) << second << endl;
58 }
59
60 // Increase this instance by one second
61 void Time::nextSecond() {
62 ++second;
63 if (second >= 60) {
64 second = 0;
65 ++minute;
66 }
67 if (minute >= 60) {
68 minute = 0;
69 ++hour;
70 }
71 if (hour >= 24) {
72 hour = 0;
73 }
}
Dissecting Time.cpp
The implementation file Time.cpp contains member's definitions (whereas the header file contains the
declarations), in particular, member functions.
All member's identifiers in the implementation are preceded by the classname and the scope resolution
operator (::), e.g., Time::Time and Time::getHour, so that the compiler can tell that these identifiers
belong to a particular class, in this case, Time.
Time::Time(int h, int m, int s) {
hour = h;
minute = m;
second = s;
}

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
In the constructor, we initialize the private data members hour, minute and second based on the inputs
provided by the caller. C++ does NOT initialize fundamental-type (e.g., int, double) data members. It
also does NOT issue an error message if you use an data member before it is initialized. Hence, It is
strongly recommended to initialize all the data members in the constructor, so that the constructed
instance is complete, instead of relying on the user to set the values of the data members after
construction.
The default values of the parameters are specified in the class declaration (in the header), NOT in the
function definition. Placing a default value in function definition (e.g., h = 0) causes a compilation error.

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 rest of the function definitions are self-explanatory.


"this" Pointer
Instead of naming the function parameters h, m and s, we would like to name the
parameters hour, minute and second, which are semantically more meaningful. However, these names
crashes with the names of private data members. C++ provides a keyword this (which is a pointer to this
instance - to be discussed later) to differentiate between the data members and function
parameters. this->hour, this->minute and this->second refer to the data members;
while hour, minute, and second refer to the function parameters. We can rewrite the constructor and
setter as follows:
Time::Time(int hour, int minute, int second) { // Constructor
this->hour = hour;
this->minute = minute;
this->second = second;
}

Time::setHour(int hour) { // Setter for hour


this->hour = hour;
}

Time::getHour() const { // Getter for hour


return this->hour; // this-> is the default, and hence optional
}

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
Member Initializer List
C++ provide an alternative syntax to initialize data members in the constructor called member initializer
list. For example,
Time::Time(int h, int m, int s) : hour(h), minute(m), second(s) {
// The body runs after the member initializer list
// empty in this case
}
The member initializer list is placed after the function parameter list, separated by a colon, in the form
of dataMemberName(parameters). For fundamental-type data members (e.g., int, double), hour(h) is the
same as hour = h. For object data members (to be discussed later), the copy constructor will be invoked.
The function body will be executed after the member initializer list, which is empty in this case.

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();

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in
31 t4.nextSecond();
32 t4.print();
33 t4.nextSecond();
34 t4.print();
35
36 // No input validation
37 Time t5(25, 61, 99); // values out of range
38 t5.print(); // 25:61:99
}
Dissecting TestTime.cpp
The test driver tests the constructor (with and without the default values) and all the public member
functions. Clearly, no input validation is carried out, as reflected in instance t5.
Exercise
Add member
functions previousSecond(), nextMinute(), previousMinute(), nextHour(), previousHour() to
the Time class.
Compiling the Program
You can compile all the source file together to get the executable file as follows:

// Using GCC on Windows


// Compile all source files, -o specifies the output
> g++ -o TestTime.exe Time.cpp TestTime.cpp
// Execute the program
> TestTime
Alternatively, you can compile Time.cpp into an object file Time.o, and then the test driver with the
object file. In this way, you only distribute the object file and header file, not the source file.
// Compile Time.cpp into object file Time.o, with -c option
> g++ -c Time.cpp
// Compile test driver with object file
> g++ -o TestTime.exe TestTime.cpp Time.o
// Execute the test driver
> TestTime

Impetus IT Services Pvt.Ltd.


B-16, First floor, Sant Tukaram Vyapar Sankul, Sector - 24, Nigdi, Pune, Maharashtra. India. Pin – 411044.
Mobile 9970600774, 9730012775|Board 91-20-27640406|Fax 91-20-27641703
Email : [email protected] | Website http://impetusits.in

You might also like