Classes : a deeper look

Download Report

Transcript Classes : a deeper look

1
CLASSES : A DEEPER
LOOK
Chapter 9
Part I
2
OBJECTIVES
In this chapter you will learn:
• How to use a preprocessor wrapper to prevent multiple definition
errors caused by including more than one copy of a header file in a
source-code file.
• To understand class scope and accessing class members via the
name of an object, a reference to an object or a pointer to an object.
• To define constructors with default arguments.
• How destructors are used to perform "termination housekeeping" on
an object before it is destroyed.
• When constructors and destructors are called and the order in
which they are called.
• The logic errors that may occur when a public member function of
a class returns a reference to private data.
• To assign the data members of one object to those of another
object by default memberwise assignment.
3
Outline
•
•
•
•
•
•
•
•
•
•
•
9.1 Introduction
9.2 Time Class Case Study
9.3 Class Scope and Accessing Class Members
9.4 Separating Interface from Implementation
9.5 Access Functions and Utility Functions
9.6 Time Class Case Study: Constructors with Default
Arguments
9.7 Destructors
9.8 When Constructors and Destructors Are Called
9.9 Time Class Case Study: A Subtle Trap—Returning a
Reference to a private Data Member
9.10 Default Memberwise Assignment
9.11 Wrap-Up
4
9.1 Introduction
• Integrated Time class case study
• Preprocessor wrapper
• Three types of “handles” on an object
• Name of an object
• Reference to an object
• Pointer to an object
• Class functions
• Predicate functions
• Utility functions
5
9.1 Introduction (cont.)
• Passing arguments to constructors
• Using default arguments in a constructor
• Destructor
• Performs “termination housekeeping”
6
9.2 Time Class Case Study
• Preprocessor wrappers
• Prevents code from being included more than once
• #ifndef – “if not defined”
• Skip this code if it has been included already
• #define
• Define a name so this code will not be included again
• #endif
• If the header has been included previously
• Name is defined already and the header file is not included again
• Prevents multiple-definition errors
• Example
• #ifndef TIME_H
#define TIME_H
… // code
#endif
7
1
// Fig. 9.1: Time.h
2
3
// Declaration of class Time.
// Member functions are defined in Time.cpp
9.2 Time Class Case Study
4
5
6
7
8
9
10
// prevent multiple inclusions of header file
#ifndef TIME_H
Preprocessor directive
#define TIME_H
// Time class definition
class Time
Outline
#ifndef determines whether a name is defined
Preprocessor directive #define defines a name (e.g., TIME_H)
11 {
12 public:
13
Time(); // constructor
14
void setTime( int, int, int ); // set hour, minute and second
15
void printUniversal(); // print time in universal-time format
16
void printStandard(); // print time in standard-time format
17 private:
18
int hour; // 0 - 23 (24-hour clock format)
19
int minute; // 0 - 59
20
int second; // 0 - 59
21 }; // end class Time
22
23 #endif
Preprocessor
directive #endif marks the end of the
code that should not be included multiple times
8
1
// Fig. 9.2: Time.cpp
2
// Member-function definitions for class Time.
3
#include <iostream>
4
using std::cout;
8
Outline
5
6
#include <iomanip>
7
using std::setfill;
8
using std::setw;
Time.cpp
(1 of 2)
9
10 #include "Time.h" // include definition of class Time from Time.h
11
12 // Time constructor initializes each data member to zero.
13 // Ensures all Time objects start in a consistent state.
14 Time::Time()
15 {
16
hour = minute = second = 0;
17 } // end Time constructor
18
Important note:
you can define
several
overloaded
constructors for a
class.
19 // set new Time value using universal time; ensure that
20 // the data remains consistent by setting invalid values to zero
21 void Time::setTime( int h, int m, int s )
22 {
23
hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
24
minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
25
second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
26 } // end function setTime
Ensure that hour, minute
and second values remain
valid
9
27
9
28 // print Time in universal-time format (HH:MM:SS)
29 void Time::printUniversal()
30 {
31
32
Outline
Using setfill stream manipulator to specify a fill character
cout << setfill( '0' ) << setw( 2 ) << hour << ":"
<< setw( 2 ) << minute << ":" << setw( 2 ) << second;
Time.cpp
33 } // end function printUniversal
(2 of 2)
34
35 // print Time in standard-time format (HH:MM:SS AM or PM)
36 void Time::printStandard()
37 {
38
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":"
39
<< setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 )
40
<< second << ( hour < 12 ? " AM" : " PM" );
41 } // end function printStandard
10
1 // Fig. 9.3: fig09_03.cpp
10
2 // Program to test class Time.
3 // NOTE: This file must be compiled with Time.cpp.
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 #include "Time.h" // include definition of class Time from Time.h
9
10 int main()
11 {
12
13
Time t; // instantiate object t of class Time
14
15
// output Time object t's initial values
cout << "The initial universal time is ";
16
17
18
t.printUniversal(); // 00:00:00
cout << "\nThe initial standard time is ";
t.printStandard(); // 12:00:00 AM
19
20
21
t.setTime( 13, 27, 6 ); // change time
22
23
// output Time object t's new values
cout << "\n\nUniversal time after setTime is ";
24
t.printUniversal(); // 13:27:06
25
26
cout << "\nStandard time after setTime is ";
t.printStandard(); // 1:27:06 PM
27
28
t.setTime( 99, 99, 99 ); // attempt invalid settings
Outline
fig09_03.cpp
(1 of 2)
11
29
11
30
// output t's values after specifying invalid values
31
cout << "\n\nAfter attempting invalid settings:"
32
Outline
<< "\nUniversal time: ";
33
t.printUniversal(); // 00:00:00
34
cout << "\nStandard time: ";
35
t.printStandard(); // 12:00:00 AM
36
cout << endl;
37
return 0;
38 } // end main
The initial universal time is 00:00:00
The initial standard time is 12:00:00 AM
Universal time after setTime is 13:27:06
Standard time after setTime is 1:27:06 PM
After attempting invalid settings:
Universal time: 00:00:00
Standard time: 12:00:00 AM
fig09_03.cpp
(2 of 2)
12
9.2 Time Class Case Study (Cont.)
• Parameterized stream manipulator setfill
• Specifies the fill character
• Which is displayed when an output field wider than the number of digits
in the output value
• By default, fill characters appear to the left of the digits in the number
• setfill is a “sticky” setting
• Applies for all subsequent values that are displayed in fields wider than
the value being displayed
13
9.2 Time Class Case Study (cont.)
• Parameterized stream manipulator setw(x) specifies that
the next value output should appear in a field width of x
• i.e. using setw(2): cout prints the value with at least 2
character position
• If the value to be output is less than 2 characters
positions wide, the value is right justified in the field by
default.
• If the value to be output is more than 2 characters
positions wide, the field width is extended to
accommodate the entire value.
• setw is applied only to the next value displayed (setw is a
“nonsticky” setting)
14
9.2 Time Class Case Study (Cont.)
• Member function declared in a class definition but
defined outside that class definition
• Still within the class’s scope
• Known only to other members of the class unless referred to via
• Object of the class
• Reference to an object of the class
• Pointer to an object of the class
• Binary scope resolution operator
• Member function defined in the body of a class definition
• C++ compiler attempts to inline calls to the member function
15
9.2 Time Class Case Study (cont.)
• C++ provides inline functions to help reduce function
call overhead –especially for small functions.
• Placing the qualifier inline before a function’s return
type in the function definition advises the compiler to
generate a copy of the function’s code in place to avoid
a function call.
16
17
9.2 Time Class Case Study (Cont.)
• Using class Time
• Once class Time has been defined, it can be used in declarations
• Time sunset; // object of type Time
• Time arrayOfTimes[ 5 ]; // array of 5 Time objects
• Time &dinnerTime = sunset; // reference to a Time object
• Time *timePtr = &dinnerTime; // pointer to a Time object
18
19
20
21
9.3 Class Scope and Accessing Class Members
• Class scope contains
• Data members
• Variables declared in the class definition
• Member functions
• Functions declared in the class definition
• Nonmember functions are defined at file scope
22
9.3 Class Scope and Accessing Class Members
(Cont.)
• Within a class’s scope
• Class members are accessible by all member functions
• Outside a class’s scope
• public class members are referenced through a handle
• An object name
• A reference to an object
• A pointer to an object
23
9.3 Class Scope and Accessing Class Members
(Cont.)
• Variables declared in a member function
• Have block scope
• Known only to that function
• Hiding a class-scope variable
• In a member function, define a variable with the same name as a
variable with class scope
• Such a hidden variable can be accessed by preceding the name
with the class name followed by the scope resolution operator (::)
24
9.3 Class Scope and Accessing Class Members
(Cont.)
• Dot member selection operator (.)
• Accesses the object’s members
• Used with an object’s name or with a reference to an object
• Arrow member selection operator (->)
• Accesses the object’s members
• Used with a pointer to an object
25
1
// Fig. 9.4: fig09_04.cpp
2
// Demonstrating the class member access operators . and ->
3
#include <iostream>
4
using std::cout;
5
using std::endl;
25
fig09_04.cpp
6
7
// class Count definition
8
class Count
9
{
10 public: // public data is dangerous
11
// sets the value of private data member x
12
void setX( int value )
13
{
x = value;
14
15
} // end function setX
16
17
// prints the value of private data member x
18
void print()
19
{
20
21
cout << x << endl;
} // end function print
22
23 private:
24
Outline
int x;
25 }; // end class Count
(1 of 2)
26
26
26
27 int main()
Outline
28 {
29
Count counter; // create counter object
30
31
Count *counterPtr = &counter; // create pointer to counter
Count &counterRef = counter; // create reference to counter
32
33
Using
theusing
dot member
selection
operator
cout << "Set x to 1 and
print
the object's
name:
";
34
counter.setX( 1 ); // set data member x to 1
35
counter.print(); // call member function print
36
fig09_04.cpp
with an object
37
38
Using using
the dot
operator
cout << "Set x to 2 and print
a member
referenceselection
to an object:
"; with
counterRef.setX( 2 ); // set data member x to 2
39
counterRef.print(); // call member function print
40
41
42
cout << "Set x to 3 and print using a pointer to an object: ";
counterPtr->setX( 3 ); // set data member x to 3
(2 of 2)
a reference
Using the arrow member selection operator with a pointer
43
counterPtr->print(); // call member function print
44
return 0;
45 } // end main
Set x to 1 and print using the object's name: 1
Set x to 2 and print using a reference to an object: 2
Set x to 3 and print using a pointer to an object: 3
27
9.4 Separating Interface from Implementation
• Separating a class definition and the class’s member-
function definitions
• Makes it easier to modify programs
• Changes in the class’s implementation do not affect the client as long as
the class’s interface remains unchanged
• Things are not quite this rosy
• Header files do contain some portions of the
implementation and hint about others
• Inline functions need to be defined in header file
• private members are listed in the class definition in the header file
28
29
9.5 Access Functions and Utility Functions
• Access functions
• Can read or display data
• Can test the truth or falsity of conditions
• Such functions are often called predicate functions
• For example, isEmpty function for a class capable of holding many
objects
• Utility functions (also called helper functions)
• private member functions that support the operation of the
class’s public member functions
• Not part of a class’s public interface
• Not intended to be used by clients of a class
30
1
// Fig. 9.5: SalesPerson.h
2
// SalesPerson class definition.
3
// Member functions defined in SalesPerson.cpp.
4
#ifndef SALESP_H
5
#define SALESP_H
30
Outline
SalesPerson.h
6
7
class SalesPerson
8
{
9
public:
(1 of 1)
10
SalesPerson(); // constructor
11
void getSalesFromUser(); // input sales from keyboard
12
void setSales( int, double ); // set sales for a specific month
13
void printAnnualSales(); // summarize and print sales
14 private:
Prototype for a private utility function
15
double totalAnnualSales(); // prototype for utility function
16
double sales[ 12 ]; // 12 monthly sales figures
17 }; // end class SalesPerson
18
19 #endif
31
1
// Fig. 9.6: SalesPerson.cpp
2
// Member functions for class SalesPerson.
3
#include <iostream>
4
using std::cout;
5
using std::cin;
6
using std::endl;
7
using std::fixed;
31
#include <iomanip>
10 using std::setprecision;
11
12 #include "SalesPerson.h" // include SalesPerson class definition
13
14 // initialize elements of array sales to 0.0
15 SalesPerson::SalesPerson()
16 {
17
18
SalesPerson.cpp
(1 of 3)
8
9
Outline
for ( int i = 0; i < 12; i++ )
sales[ i ] = 0.0;
19 } // end SalesPerson constructor
32
20
32
21 // get 12 sales figures from the user at the keyboard
22 void SalesPerson::getSalesFromUser()
23 {
24
double salesFigure;
25
26
27
for ( int i = 1; i <= 12; i++ )
{
28
29
30
31
cout << "Enter sales amount for month " << i << ": ";
cin >> salesFigure;
setSales( i, salesFigure );
} // end for
32 } // end function getSalesFromUser
33
34 // set one of the 12 monthly sales figures; function subtracts
35 // one from month value for proper subscript in sales array
36 void SalesPerson::setSales( int month, double amount )
37 {
38
39
40
// test for valid month and amount values
if ( month >= 1 && month <= 12 && amount > 0 )
sales[ month - 1 ] = amount; // adjust for subscripts 0-11
41
42
else // invalid month or amount value
cout << "Invalid month or sales figure" << endl;
43 } // end function setSales
Outline
SalesPerson.cpp
(2 of 3)
33
44
33
45 // print total annual sales (with the help of utility function)
46 void SalesPerson::printAnnualSales()
47 {
48
cout << setprecision( 2 ) << fixed
Outline
Calling a private utility function
SalesPerson.cpp
49
<< "\nThe total annual sales are: $"
50
<< totalAnnualSales() << endl; // call utility function
(3 of 3)
51 } // end function printAnnualSales
52
53 // private utility function to total annual sales
54 double SalesPerson::totalAnnualSales()
55 {
56
double total = 0.0; // initialize total
Definition of a private utility function
57
58
for ( int i = 0; i < 12; i++ ) // summarize sales results
59
total += sales[ i ]; // add month i sales to total
60
61
return total;
62 } // end function totalAnnualSales
34
1
// Fig. 9.7: fig09_07.cpp
2
// Demonstrating a utility function.
3
// Compile this program with SalesPerson.cpp
34
Outline
4
5
// include SalesPerson class definition from SalesPerson.h
6
#include "SalesPerson.h"
fig09_07.cpp
8
int main()
(1 of 1)
9
{
7
10
SalesPerson s; // create SalesPerson object s
11
12
s.getSalesFromUser(); // note simple sequential code;
13
s.printAnnualSales(); // no control statements in main
14
return 0;
15 } // end main
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
sales
sales
sales
sales
sales
sales
sales
sales
sales
sales
sales
sales
amount
amount
amount
amount
amount
amount
amount
amount
amount
amount
amount
amount
for
for
for
for
for
for
for
for
for
for
for
for
month
month
month
month
month
month
month
month
month
month
month
month
1: 5314.76
2: 4292.38
3: 4589.83
4: 5534.03
5: 4376.34
6: 5698.45
7: 4439.22
8: 5893.57
9: 4909.67
10: 5123.45
11: 4024.97
12: 5923.92
The total annual sales are: $60120.59
35
9.6 Time Class Case Study: Constructors with
Default Arguments
• Constructors can specify default arguments
• Can initialize data members to a consistent state
• Even if no values are provided in a constructor call
• Constructor that defaults all its arguments is also a
default constructor
• Can be invoked with no arguments
• Maximum of one default constructor per class
36
1
// Fig. 9.8: Time.h
2
// Declaration of class Time.
3
// Member functions defined in Time.cpp.
36
Outline
4
5
// prevent multiple inclusions of header file
6
#ifndef TIME_H
7
#define TIME_H
Time.h
(1 of 2)
8
9
// Time abstract data type definition
10 class Time
11 {
Prototype of a constructor with default arguments
12 public:
13
Time( int = 0, int = 0, int = 0 ); // default constructor
14
15
// set functions
16
void setTime( int, int, int ); // set hour, minute, second
17
void setHour( int ); // set hour (after validation)
18
void setMinute( int ); // set minute (after validation)
19
void setSecond( int ); // set second (after validation)
37
20
37
21
// get functions
22
int getHour(); // return hour
23
int getMinute(); // return minute
24
int getSecond(); // return second
Outline
Time.h
25
26
void printUniversal(); // output time in universal-time format
27
void printStandard(); // output time in standard-time format
28 private:
29
int hour; // 0 - 23 (24-hour clock format)
30
int minute; // 0 - 59
31
int second; // 0 - 59
32 }; // end class Time
33
34 #endif
(2 of 2)
38
1
// 38
Fig. 9.9: Time.cpp
2
// Member-function definitions for class Time.
3
#include <iostream>
4
using std::cout;
Outline
5
6
#include <iomanip>
7
using std::setfill;
8
using std::setw;
Time.cpp
(1 of 3)
9
10 #include "Time.h" // include definition of class Time from Time.h
11
12 // Time constructor initializes each data member to zero;
13 // ensures that Time objects start in a consistent state
14 Time::Time( int hr, int min, int sec )
15 {
16
setTime( hr, min, sec ); // validate and set time
Parameters could receive the default values
17 } // end Time constructor
18
19 // set new Time value using universal time; ensure that
20 // the data remains consistent by setting invalid values to zero
21 void Time::setTime( int h, int m, int s )
22 {
23
setHour( h ); // set private field hour
24
setMinute( m ); // set private field minute
25
setSecond( s ); // set private field second
26 } // end function setTime
39
27
39
28 // set hour value
29 void Time::setHour( int h )
30 {
31
hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
32 } // end function setHour
33
34 // set minute value
35 void Time::setMinute( int m )
36 {
37
minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
38 } // end function setMinute
39
40 // set second value
41 void Time::setSecond( int s )
42 {
43
second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
44 } // end function setSecond
45
46 // return hour value
47 int Time::getHour()
48 {
49
return hour;
50 } // end function getHour
51
52 // return minute value
53 int Time::getMinute()
54 {
55
return minute;
56 } // end function getMinute
Outline
Time.cpp
(2 of 3)
40
57
40
58 // return second value
59 int Time::getSecond()
Outline
60 {
61
return second;
62 } // end function getSecond
Time.cpp
63
64 // print Time in universal-time format (HH:MM:SS)
65 void Time::printUniversal()
66 {
67
68
cout << setfill( '0' ) << setw( 2 ) << getHour() << ":"
<< setw( 2 ) << getMinute() << ":" << setw( 2 ) << getSecond();
69 } // end function printUniversal
70
71 // print Time in standard-time format (HH:MM:SS AM or PM)
72 void Time::printStandard()
73 {
74
cout << ( ( getHour() == 0 || getHour() == 12 ) ? 12 : getHour() % 12 )
75
<< ":" << setfill( '0' ) << setw( 2 ) << getMinute()
76
<< ":" << setw( 2 ) << getSecond() << ( hour < 12 ? " AM" : " PM" );
77 } // end function printStandard
(3 of 3)
41
9.6 Time Class Case Study: Constructors
with Default Arguments (cont.)
• Calling setHour, setMinute and setSecond from the
constructor may be slightly more efficient because the extra call to
setTime would be eliminated.
• Similarly, copying the code from lines 27, 33 and 39 into
constructor would eliminate the overhead of calling setTime,
setHour, setMinute and setSecond.
• This would make maintenance of this class more difficult.
• If the implementations of setHour, setMinute and setSecond
were to change, the implementation of any member function that
duplicates lines 27, 33 and 39 would have to change accordingly.
• Calling setTime and having setTime call setHour,
setMinute and setSecond enables us to limit the changes to
the corresponding set function.
• Reduces the likelihood of errors when altering the implementation.
42
43
1
2
// Fig. 9.10: fig09_10.cpp
43
// Demonstrating a default constructor for class Time.
3
4
5
#include <iostream>
using std::cout;
using std::endl;
6
7
8
#include "Time.h" // include definition of class Time from Time.h
Outline
fig09_10.cpp
(1 of 3)
9 int main()
10 {
Initializing Time objects
using 0, 1, 2 and 3 arguments
11
12
Time t1; // all arguments defaulted
Time t2( 2 ); // hour specified; minute and second defaulted
13
14
15
16
Time t3( 21, 34 ); // hour and minute specified; second defaulted
Time t4( 12, 25, 42 ); // hour, minute and second specified
Time t5( 27, 74, 99 ); // all bad values specified
17
cout << "Constructed with:\n\nt1: all arguments defaulted\n
18
19
20
21
t1.printUniversal(); // 00:00:00
cout << "\n ";
t1.printStandard(); // 12:00:00 AM
22
23
24
cout << "\n\nt2: hour specified; minute and second defaulted\n
t2.printUniversal(); // 02:00:00
cout << "\n ";
25
t2.printStandard(); // 2:00:00 AM
";
";
44
26
27
28
44
cout << "\n\nt3: hour and minute specified; second defaulted\n
t3.printUniversal(); // 21:34:00
29
cout << "\n
30
31
32
33
34
35
t3.printStandard(); // 9:34:00 PM
";
Outline
";
cout << "\n\nt4: hour, minute and second specified\n
t4.printUniversal(); // 12:25:42
cout << "\n ";
t4.printStandard(); // 12:25:42 PM
36
37
cout << "\n\nt5: all invalid values specified\n
38
39
40
t5.printUniversal(); // 00:00:00
cout << "\n ";
t5.printStandard(); // 12:00:00 AM
41
cout << endl;
42
return 0;
43 } // end main
";
";
fig09_10.cpp
(2 of 3)
45
45
Constructed with:
Outline
t1: all arguments defaulted
00:00:00
12:00:00 AM
t2: hour specified; minute and second defaulted
02:00:00
2:00:00 AM
fig09_10.cpp
(3 of 3)
t3: hour and minute specified; second defaulted
21:34:00
9:34:00 PM
t4: hour, minute and second specified
12:25:42
12:25:42 PM
t5: all invalid values specified
00:00:00
12:00:00 AM
Invalid values passed to constructor,
so object t5 contains all default data
46
9.6 Time Class Case Study: Constructors
with Default Arguments (cont.)
• Time’s set and get functions are called throughout the class’s
body.
• In each case, these functions could have accessed the class’s
private data directly.
• Consider changing the representation of the time from three
int values (requiring 12 bytes of memory) to a single int
value representing the total number of seconds that have
elapsed since midnight (requiring only four bytes of
memory).
• If we made such a change, only the bodies of the functions
that access the private data directly would need to
change.
• No need to modify the bodies of the other functions.
47
9.6 Time Class Case Study: Constructors
with Default Arguments (cont.)
• Designing the class in this manner reduces the likelihood of
programming errors when altering the class’s implementation.
• Duplicating statements in multiple functions or constructors
makes changing the class’s internal data representation more
difficult.