0% found this document useful (0 votes)
61 views62 pages

Classes: A Deeper Look,: 2006 Pearson Education, Inc. All Rights Reserved

The document describes a Time class with methods to set the time, print the time in universal and standard formats, and a test program. The Time class has private data members for hour, minute and second. Methods validate the values and reset them to valid ranges. The test program instantiates a Time object, sets the time, and prints the initial and changed times to demonstrate the class functionality.

Uploaded by

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

Classes: A Deeper Look,: 2006 Pearson Education, Inc. All Rights Reserved

The document describes a Time class with methods to set the time, print the time in universal and standard formats, and a test program. The Time class has private data members for hour, minute and second. Methods validate the values and reset them to valid ranges. The test program instantiates a Time object, sets the time, and prints the initial and changed times to demonstrate the class functionality.

Uploaded by

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

1

9
Classes:
A Deeper Look,
Part 1
 2006 Pearson Education, Inc. All rights reserved.
2

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 Software Reusability
9.12 (Optional) Software Engineering Case Study: Starting to
Program the Classes of the ATM System
9.13 Wrap-Up

 2006 Pearson Education, Inc. All rights reserved.


3

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

 2006 Pearson Education, Inc. All rights reserved.


4

9.1 Introduction (Cont.)


• Passing arguments to constructors
• Using default arguments in a constructor
• Destructor
– Performs “termination housekeeping”

 2006 Pearson Education, Inc. All rights reserved.


5

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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.1: Time.h
6
2
3
// Declaration of class Time.
// Member functions are defined in Time.cpp
Outline
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME_H Preprocessor directive #ifndef determines whether a name is defined
Time.h
7 #define TIME_H
8
9 // Time class definition
(1 of 1)
Preprocessor directive #define defines a name (e.g., TIME_H)
10 class Time
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

 2006 Pearson Education,


Inc. All rights reserved.
7

Error-Prevention Tip 9.1

Use #ifndef, #define and #endif


preprocessor directives to form a preprocessor
wrapper that prevents header files from being
included more than once in a program.

 2006 Pearson Education, Inc. All rights reserved.


8

Good Programming Practice 9.2

Use the name of the header file in upper case with


the period replaced by an underscore in the
#ifndef and #define preprocessor directives
of a header file.

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.2: Time.cpp
9
2 // Member-function definitions for class Time.
Outline
3 #include <iostream>
4 using std::cout;
5
6 #include <iomanip> Time.cpp
7 using std::setfill;
8 using std::setw; (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
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 ) Ensure that hour, minute and
22 { second values remain valid
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

 2006 Pearson Education,


Inc. All rights reserved.
27
10
28 // print Time in universal-time format (HH:MM:SS)
Outline
29 void Time::printUniversal()
30 { Using setfill stream manipulator to specify a fill character
31 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
32 << setw( 2 ) << minute << ":" << setw( 2 ) << second; Time.cpp
33 } // end function printUniversal
34 (2 of 2)
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

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.3: fig09_03.cpp
11
2 // Program to test class Time.
3 // NOTE: This file must be compiled with Time.cpp.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::endl;
fig09_03.cpp
7
8 #include "Time.h" // include definition of class Time from Time.h
9
(1 of 2)
10 int main()
11 {
12 Time t; // instantiate object t of class Time
13
14 // output Time object t's initial values
15 cout << "The initial universal time is ";
16 t.printUniversal(); // 00:00:00
17 cout << "\nThe initial standard time is ";
18 t.printStandard(); // 12:00:00 AM
19
20 t.setTime( 13, 27, 6 ); // change time
21
22 // output Time object t's new values
23 cout << "\n\nUniversal time after setTime is ";
24 t.printUniversal(); // 13:27:06
25 cout << "\nStandard time after setTime is ";
26 t.printStandard(); // 1:27:06 PM
27
28 t.setTime( 99, 99, 99 ); // attempt invalid settings

 2006 Pearson Education,


Inc. All rights reserved.
29
12
30 // output t's values after specifying invalid values
Outline
31 cout << "\n\nAfter attempting invalid settings:"
32 << "\nUniversal time: ";
33 t.printUniversal(); // 00:00:00
34 cout << "\nStandard time: "; fig09_03.cpp
35 t.printStandard(); // 12:00:00 AM
36 cout << endl; (2 of 2)
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

 2006 Pearson Education,


Inc. All rights reserved.
13

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

 2006 Pearson Education, Inc. All rights reserved.


14

9.2 Time Class Case Study (Cont.)


• Using class Time
– Once class Time has been defined, it can be used in
declarations
• Time sunset;
• Time arrayOfTimes[ 5 ];
• Time &dinnerTime = sunset;
• Time *timePtr = &dinnerTime;

 2006 Pearson Education, Inc. All rights reserved.


15
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

 2006 Pearson Education, Inc. All rights reserved.


16
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

 2006 Pearson Education, Inc. All rights reserved.


17
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 (::)

 2006 Pearson Education, Inc. All rights reserved.


18
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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.4: fig09_04.cpp
19
2 // Demonstrating the class member access operators . and ->
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig09_04.cpp
7 // class Count definition
8 class Count (1 of 2)
9 {
10 public: // public data is dangerous
11 // sets the value of private data member x
12 void setX( int value )
13 {
14 x = value;
15 } // end function setX
16
17 // prints the value of private data member x
18 void print()
19 {
20 cout << x << endl;
21 } // end function print
22
23 private:
24 int x;
25 }; // end class Count

 2006 Pearson Education,


Inc. All rights reserved.
26
20
27 int main()
28 {
Outline
29 Count counter; // create counter object
30 Count *counterPtr = &counter; // create pointer to counter
31 Count &counterRef = counter; // create reference to counter
fig09_04.cpp
32
33 Using
cout << "Set x to 1 and printthe dot member
using selection
the object's name:operator
"; with an object
34 counter.setX( 1 ); // set data member x to 1
(2 of 2)
35 counter.print(); // call member function print
36
37 Usingusing
cout << "Set x to 2 and print the dot
a member
referenceselection operator
to an object: "; with a reference
38 counterRef.setX( 2 ); // set data member x to 2
39 counterRef.print(); // call member function print
40
Using the arrow member selection operator with a pointer
41 cout << "Set x to 3 and print using a pointer to an object: ";
42 counterPtr->setX( 3 ); // set data member x to 3
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

 2006 Pearson Education,


Inc. All rights reserved.
21
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

 2006 Pearson Education, Inc. All rights reserved.


22
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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.5: SalesPerson.h
23
2 // SalesPerson class definition.
Outline
3 // Member functions defined in SalesPerson.cpp.
4 #ifndef SALESP_H
5 #define SALESP_H
6 SalesPerson.h
7 class SalesPerson
8 { (1 of 1)
9 public:
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

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.6: SalesPerson.cpp
24
2 // Member functions for class SalesPerson.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::cin;
6 using std::endl; SalesPerson.cpp
7 using std::fixed;
8 (1 of 3)
9 #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 for ( int i = 0; i < 12; i++ )
18 sales[ i ] = 0.0;
19 } // end SalesPerson constructor

 2006 Pearson Education,


Inc. All rights reserved.
20
25
21 // get 12 sales figures from the user at the keyboard
22 void SalesPerson::getSalesFromUser()
Outline
23 {
24 double salesFigure;
25
SalesPerson.cpp
26 for ( int i = 1; i <= 12; i++ )
27 {
28 cout << "Enter sales amount for month " << i << ": ";
(2 of 3)
29 cin >> salesFigure;
30 setSales( i, salesFigure );
31 } // 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 // test for valid month and amount values
39 if ( month >= 1 && month <= 12 && amount > 0 )
40 sales[ month - 1 ] = amount; // adjust for subscripts 0-11
41 else // invalid month or amount value
42 cout << "Invalid month or sales figure" << endl;
43 } // end function setSales

 2006 Pearson Education,


Inc. All rights reserved.
44
26
45 // print total annual sales (with the help of utility function)
Outline
46 void SalesPerson::printAnnualSales()
47 {
48 cout << setprecision( 2 ) << fixed
Calling a private utility function
49 << "\nThe total annual sales are: $" SalesPerson.cpp
50 << totalAnnualSales() << endl; // call utility function
51 } // end function printAnnualSales (3 of 3)
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

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.7: fig09_07.cpp
27
2 // Demonstrating a utility function.
Outline
3 // Compile this program with SalesPerson.cpp
4
5 // include SalesPerson class definition from SalesPerson.h
6 #include "SalesPerson.h" fig09_07.cpp
7
8 int main() (1 of 1)
9 {
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 sales amount for month 1: 5314.76


Enter sales amount for month 2: 4292.38
Enter sales amount for month 3: 4589.83
Enter sales amount for month 4: 5534.03
Enter sales amount for month 5: 4376.34
Enter sales amount for month 6: 5698.45
Enter sales amount for month 7: 4439.22
Enter sales amount for month 8: 5893.57
Enter sales amount for month 9: 4909.67
Enter sales amount for month 10: 5123.45
Enter sales amount for month 11: 4024.97
Enter sales amount for month 12: 5923.92

The total annual sales are: $60120.59

 2006 Pearson Education,


Inc. All rights reserved.
28
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

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.8: Time.h
29
2 // Declaration of class Time.
Outline
3 // Member functions defined in Time.cpp.
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME_H Time.h
7 #define TIME_H
8 (1 of 2)
9 // Time abstract data type definition
10 class Time
Prototype of a constructor with default arguments
11 {
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)

 2006 Pearson Education,


Inc. All rights reserved.
20
30
21 // get functions
Outline
22 int getHour(); // return hour
23 int getMinute(); // return minute
24 int getSecond(); // return second
25 Time.h
26 void printUniversal(); // output time in universal-time format
27 void printStandard(); // output time in standard-time format (2 of 2)
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

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.9: Time.cpp
31
2 // Member-function definitions for class Time.
Outline
3 #include <iostream>
4 using std::cout;
5
6 #include <iomanip> Time.cpp
7 using std::setfill;
8 using std::setw; (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

 2006 Pearson Education,


Inc. All rights reserved.
27
32
28
29
// set hour value
void Time::setHour( int h )
Outline
30 {
31 hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
32 } // end function setHour
Time.cpp
33
34 // set minute value
35 void Time::setMinute( int m )
(2 of 3)
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

 2006 Pearson Education,


Inc. All rights reserved.
57
33
58 // return second value
Outline
59 int Time::getSecond()
60 {
61 return second;
62 } // end function getSecond Time.cpp
63
64 // print Time in universal-time format (HH:MM:SS) (3 of 3)
65 void Time::printUniversal()
66 {
67 cout << setfill( '0' ) << setw( 2 ) << getHour() << ":"
68 << 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

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.10: fig09_10.cpp
34
2
3
// Demonstrating a default constructor for class Time.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig09_10.cpp
7 #include "Time.h" // include definition of class Time from Time.h
8
9 int main()
(1 of 3)
10 { Initializing Time objects
11 Time t1; // all arguments defaulted
using 0, 1, 2 and 3 arguments
12 Time t2( 2 ); // hour specified; minute and second defaulted
13 Time t3( 21, 34 ); // hour and minute specified; second defaulted
14 Time t4( 12, 25, 42 ); // hour, minute and second specified
15 Time t5( 27, 74, 99 ); // all bad values specified
16
17 cout << "Constructed with:\n\nt1: all arguments defaulted\n ";
18 t1.printUniversal(); // 00:00:00
19 cout << "\n ";
20 t1.printStandard(); // 12:00:00 AM
21
22 cout << "\n\nt2: hour specified; minute and second defaulted\n ";
23 t2.printUniversal(); // 02:00:00
24 cout << "\n ";
25 t2.printStandard(); // 2:00:00 AM

 2006 Pearson Education,


Inc. All rights reserved.
26
35
27
28
cout << "\n\nt3: hour and minute specified; second defaulted\n
t3.printUniversal(); // 21:34:00
";
Outline
29 cout << "\n ";
30 t3.printStandard(); // 9:34:00 PM
31
fig09_10.cpp
32 cout << "\n\nt4: hour, minute and second specified\n ";
33 t4.printUniversal(); // 12:25:42
34 cout << "\n ";
(2 of 3)
35 t4.printStandard(); // 12:25:42 PM
36
37 cout << "\n\nt5: all invalid values specified\n ";
38 t5.printUniversal(); // 00:00:00
39 cout << "\n ";
40 t5.printStandard(); // 12:00:00 AM
41 cout << endl;
42 return 0;
43 } // end main

 2006 Pearson Education,


Inc. All rights reserved.
36
Constructed with:
Outline
t1: all arguments defaulted
00:00:00
12:00:00 AM

t2: hour specified; minute and second defaulted


fig09_10.cpp
02:00:00
2:00:00 AM (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

 2006 Pearson Education,


Inc. All rights reserved.
37

9.7 Destructors
• Destructor
– A special member function
– Name is the tilde character (~) followed by the class name,
e.g., ~Time
– Called implicitly when an object is destroyed
• For example, this occurs as an automatic object is destroyed
when program execution leaves the scope in which that
object was instantiated
– Does not actually release the object’s memory
• It performs termination housekeeping
• Then the system reclaims the object’s memory
– So the memory may be reused to hold new objects

 2006 Pearson Education, Inc. All rights reserved.


38

9.7 Destructors (Cont.)


• Destructor (Cont.)
– Receives no parameters and returns no value
• May not specify a return type—not even void
– A class may have only one destructor
• Destructor overloading is not allowed
– If the programmer does not explicitly provide a destructor,
the compiler creates an “empty” destructor

 2006 Pearson Education, Inc. All rights reserved.


39

Common Programming Error 9.3

It is a syntax error to attempt to pass arguments


to a destructor, to specify a return type for a
destructor (even void cannot be specified), to
return values from a destructor or to overload a
destructor.

 2006 Pearson Education, Inc. All rights reserved.


40
9.8 When Constructors and Destructors
Are Called
• Constructors and destructors
– Called implicitly by the compiler
• Order of these function calls depends on the order in which
execution enters and leaves the scopes where the objects are
instantiated
– Generally,
• Destructor calls are made in the reverse order of the
corresponding constructor calls
– However,
• Storage classes of objects can alter the order in which
destructors are called

 2006 Pearson Education, Inc. All rights reserved.


41
9.8 When Constructors and Destructors
Are Called (Cont.)
• For objects defined in global scope
– Constructors are called before any other function
(including main) in that file begins execution
– The corresponding destructors are called when main
terminates
• Function exit
– Forces a program to terminate immediately
• Does not execute the destructors of automatic objects
– Often used to terminate a program when an error is detected
• Function abort
– Performs similarly to function exit
• But forces the program to terminate immediately without
allowing the destructors of any objects to be called
– Usually used to indicate an abnormal termination of the
program

 2006 Pearson Education, Inc. All rights reserved.


42
9.8 When Constructors and Destructors
Are Called (Cont.)
• For an automatic local object
– Constructor is called when that object is defined
– Corresponding destructor is called when execution leaves
the object’s scope
• For automatic objects
– Constructors and destructors are called each time
execution enters and leaves the scope of the object
– Automatic object destructors are not called if the program
terminates with an exit or abort function

 2006 Pearson Education, Inc. All rights reserved.


43
9.8 When Constructors and Destructors
Are Called (Cont.)
• For a static local object
– Constructor is called only once
• When execution first reaches where the object is defined
– Destructor is called when main terminates or the program
calls function exit
• Destructor is not called if the program terminates with a call
to function abort
• Global and static objects are destroyed in the
reverse order of their creation

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.11: CreateAndDestroy.h
44
2 // Definition of class CreateAndDestroy.
Outline
3 // Member functions defined in CreateAndDestroy.cpp.
4 #include <string>
5 using std::string;
6 CreateAndDestroy.h
7 #ifndef CREATE_H
8 #define CREATE_H (1 of 1)
9
10 class CreateAndDestroy
11 {
12 public:
13 CreateAndDestroy( int, string ); // constructor
14 ~CreateAndDestroy(); // destructor
15 private:
16 int objectID; // ID number for object Prototype for destructor
17 string message; // message describing object
18 }; // end class CreateAndDestroy
19
20 #endif

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.12: CreateAndDestroy.cpp
45
2 // Member-function definitions for class CreateAndDestroy.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 CreateAndDestroy.
7 #include "CreateAndDestroy.h"// include CreateAndDestroy class definition cpp
8
9 // constructor (1 of 1)
10 CreateAndDestroy::CreateAndDestroy( int ID, string messageString )
11 {
12 objectID = ID; // set object's ID number
13 message = messageString; // set object's descriptive message
14
15 cout << "Object " << objectID << " constructor runs "
16 << message << endl;
17 } // end CreateAndDestroy constructor
18
19 // destructor Defining the class’s destructor
20 CreateAndDestroy::~CreateAndDestroy()
21 {
22 // output newline for certain objects; helps readability
23 cout << ( objectID == 1 || objectID == 6 ? "\n" : "" );
24
25 cout << "Object " << objectID << " destructor runs "
26 << message << endl;
27 } // end ~CreateAndDestroy destructor

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.13: fig09_13.cpp
46
2 // Demonstrating the order in which constructors and Outline
3 // destructors are called.
4 #include <iostream>
5 using std::cout;
6 using std::endl; Fig09_13.cpp
7
8 #include "CreateAndDestroy.h" // include CreateAndDestroy class definition (1 of 3)
9
10 void create( void ); // prototype
11
12 CreateAndDestroy first( 1, "(global before main)" ); // global object
13
14 int main() Object created outside of main
15 {
16 cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl;
17 CreateAndDestroy second( 2, "(local automatic in main)" );
18 static CreateAndDestroy third( 3, "(local static in main)" );
19 Local automatic object created in main
20 create(); // call function to create objects
Local static object created in main
21
22 cout << "\nMAIN FUNCTION: EXECUTION RESUMES" << endl;
23 CreateAndDestroy fourth( 4, "(local automatic in main)" );
24 cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl;
25 return 0; Local automatic object created in main
26 } // end main

 2006 Pearson Education,


Inc. All rights reserved.
27
47
28 // function to create objects
Outline
29 void create( void )
30 {
31 cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl;
32 CreateAndDestroy fifth( 5, "(local automatic in create)" ); Fig09_13.cpp
33 Local
static CreateAndDestroy sixth( 6, "(local static in automatic object
create)" ); created in create
34 CreateAndDestroy seventh( 7, "(local automatic in create)" ); (2 of 3)
35 cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl; Local static object created in create
36 } // end function create

Local automatic object created in create

 2006 Pearson Education,


Inc. All rights reserved.
Object 1 constructor runs (global before main) 48
Outline
MAIN FUNCTION: EXECUTION BEGINS
Object 2 constructor runs (local automatic in main)
Object 3 constructor runs (local static in main)

CREATE FUNCTION: EXECUTION BEGINS Fig09_13.cpp


Object 5 constructor runs (local automatic in create)
Object 6 constructor runs (local static in create) (3 of 3)
Object 7 constructor runs (local automatic in create)

CREATE FUNCTION: EXECUTION ENDS


Object 7 destructor runs (local automatic in create)
Object 5 destructor runs (local automatic in create)

MAIN FUNCTION: EXECUTION RESUMES


Object 4 constructor runs (local automatic in main)

MAIN FUNCTION: EXECUTION ENDS


Object 4 destructor runs (local automatic in main)
Object 2 destructor runs (local automatic in main)

Object 6 destructor runs (local static in create)


Object 3 destructor runs (local static in main)

Object 1 destructor runs (global before main)

 2006 Pearson Education,


Inc. All rights reserved.
49
9.9 Time Class Case Study: A Subtle Trap—
Returning a Reference to a private Data Member

• Returning a reference to an object


– Alias for the name of an object
• An acceptable lvalue that can receive a value
– May be used on the left side of an assignment statement
• If a function returns a const reference
– That reference cannot be used as a modifiable lvalue
– One (dangerous) way to use this capability
• A public member function of a class returns a reference to
a private data member of that class
– Client code could alter private data
– Same problem would occur if a pointer to private
data were returned

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.14: Time.h
50
2 // Declaration of class Time.
Outline
3 // Member functions defined in Time.cpp
4
5 // prevent multiple inclusions of header file
6 #ifndef TIME_H Time.h
7 #define TIME_H
8 (1 of 1)
9 class Time
10 {
11 public:
12 Time( int = 0, int = 0, int = 0 );
13 void setTime( int, int, int );
14 int getHour();
15 int &badSetHour( int ); // DANGEROUS reference return
16 private:
17 int hour;
18 int minute;
Prototype for function that
19 int second;
20 }; // end class Time
returns a reference
21
22 #endif

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.15: Time.cpp
51
2 // Member-function definitions for Time class.
Outline
3 #include "Time.h" // include definition of class Time
4
5 // constructor function to initialize private data;
6 // calls member function setTime to set variables; Time.cpp
7 // default values are 0 (see class definition)
8 Time::Time( int hr, int min, int sec ) (1 of 2)
9 {
10 setTime( hr, min, sec );
11 } // end Time constructor
12
13 // set values of hour, minute and second
14 void Time::setTime( int h, int m, int s )
15 {
16 hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
17 minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
18 second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
19 } // end function setTime

 2006 Pearson Education,


Inc. All rights reserved.
20
52
21 // return hour value
Outline
22 int Time::getHour()
23 {
24 return hour;
25 } // end function getHour Time.cpp
26
27 // POOR PROGRAMMING PRACTICE: (2 of 2)
28 // Returning a reference to a private data member.
29 int &Time::badSetHour( int hh )
30 {
31 hour = ( hh >= 0 && hh < 24 ) ? hh : 0;
32 return hour; // DANGEROUS reference return
33 } // end function badSetHour
Returning a reference to a private
data member = DANGEROUS!

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.16: fig09_16.cpp
53
2 // Demonstrating a public member function that
Outline
3 // returns a reference to a private data member.
4 #include <iostream>
5 using std::cout;
6 using std::endl; Fig09_16.cpp
7
8 #include "Time.h" // include definition of class Time (1 of 2)
9
10 int main()
11 {
12 Time t; // create Time object
13
14 // initialize hourRef with the reference returned by badSetHour
15 int &hourRef = t.badSetHour( 20 ); // 20 is a valid hour
16
17 cout << "Valid hour before modification: " << hourRef;
18 hourRef = 30; // use hourRef to set invalid value in Time object t
19 cout << "\nInvalid hour after modification: " << t.getHour();

Modifying a private data member


through a returned reference

 2006 Pearson Education,


Inc. All rights reserved.
20 54
21 // Dangerous: Function call that returns Outline
22 // a reference can be used as an lvalue!
23 t.badSetHour( 12 ) = 74; // assign another invalid value to hour
24
25 cout << "\n\n*************************************************\n" Fig09_16.cpp
26 << "POOR PROGRAMMING
Modifying private data by using
PRACTICE!!!!!!!!\n"
27 << "t.badSetHour( 12
a function call as an lvalue
) as an lvalue, invalid hour: " (2 of 2)
28 << t.getHour()
29 << "\n*************************************************" << endl;
30 return 0;
31 } // end main

Valid hour before modification: 20


Invalid hour after modification: 30

*************************************************
POOR PROGRAMMING PRACTICE!!!!!!!!
t.badSetHour( 12 ) as an lvalue, invalid hour: 74
*************************************************

 2006 Pearson Education,


Inc. All rights reserved.
55

9.10 Default Memberwise Assignment

• Default memberwise assignment


– Assignment operator (=)
• Can be used to assign an object to another object of the same
type
– Each data member of the right object is assigned to the
same data member in the left object
• Can cause serious problems when data members contain
pointers to dynamically allocated memory

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 9.17: Date.h 56
2 // Declaration of class Date. Outline
3 // Member functions are defined in Date.cpp
4
5 // prevent multiple inclusions of header file
6 #ifndef DATE_H Date.h
7 #define DATE_H
8 (1 of 1)
9 // class Date definition
10 class Date
11 {
12 public:
13 Date( int = 1, int = 1, int = 2000 ); // default constructor
14 void print();
15 private:
16 int month;
17 int day;
18 int year;
19 }; // end class Date
20
21 #endif

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.18: Date.cpp
57
2 // Member-function definitions for class Date.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 Date.cpp
7 #include "Date.h" // include definition of class Date from Date.h
8 (1 of 1)
9 // Date constructor (should do range checking)
10 Date::Date( int m, int d, int y )
11 {
12 month = m;
13 day = d;
14 year = y;
15 } // end constructor Date
16
17 // print Date in the format mm/dd/yyyy
18 void Date::print()
19 {
20 cout << month << '/' << day << '/' << year;
21 } // end function print

 2006 Pearson Education,


Inc. All rights reserved.
1 // Fig. 9.19: fig09_19.cpp
58
2
3
// Demonstrating that class objects can be assigned
// to each other using default memberwise assignment.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::endl;
fig09_19.cpp
7
8 #include "Date.h" // include definition of class Date from Date.h
9
(1 of 1)
10 int main()
11 {
12 Date date1( 7, 4, 2004 );
13 Date date2; // date2 defaults to 1/1/2000
14
15 cout << "date1 = ";
16 date1.print();
17 cout << "\ndate2 = "; Memberwise assignment assigns data
18 date2.print(); members of date1 to date2
19
20 date2 = date1; // default memberwise assignment
21
22 cout << "\n\nAfter default memberwise assignment, date2 = ";
23 date2.print();
24 cout << endl;
25 return 0; date2 now stores the
26 } // end main same date as date1
date1 = 7/4/2004
date2 = 1/1/2000

After default memberwise assignment, date2 = 7/4/2004


 2006 Pearson Education,
Inc. All rights reserved.
59
9.10 Default Memberwise Assignment
(Cont.)
• Copy constructor
– Enables pass-by-value for objects
• Used to copy original object’s values into new object to be
passed to a function or returned from a function
– Compiler provides a default copy constructor
• Copies each member of the original object into the
corresponding member of the new object (i.e., memberwise
assignment)
– Also can cause serious problems when data members
contain pointers to dynamically allocated memory

 2006 Pearson Education, Inc. All rights reserved.


60

Performance Tip 9.3

Passing an object by value is good from a security


standpoint, because the called function has no access to
the original object in the caller, but pass-by-value can
degrade performance when making a copy of a large
object. An object can be passed by reference by passing
either a pointer or a reference to the object. Pass-by-
reference offers good performance but is weaker from a
security standpoint, because the called function is given
access to the original object. Pass-by-const-reference is
a safe, good-performing alternative (this can be
implemented with a const reference parameter or with
a pointer-to-const-data parameter).

 2006 Pearson Education, Inc. All rights reserved.


61

9.11 Software Reusability


• Many substantial class libraries exist and others
are being developed worldwide
• Software is increasingly being constructed from
existing, well-defined, carefully tested, well-
documented, portable, high-performance, widely
available components
• Rapid applications development (RAD)
– Speeds the development of powerful, high-quality software
through the mechanisms of reusable componentry

 2006 Pearson Education, Inc. All rights reserved.


62

9.11 Software Reusability (Cont.)


• Problems to solve before realizing the full potential of
software reusability
– Cataloging schemes
– Licensing schemes
– Protection mechanisms to ensure that master copies of classes
are not corrupted
– Description schemes so that designers of new systems can easily
determine whether existing objects meet their needs
– Browsing mechanisms to determine what classes are available
and how closely they meet software developer requirements
– Research and development problems
• Great motivation to solve these problems
– Potential value of their solutions is enormous

 2006 Pearson Education, Inc. All rights reserved.

You might also like