1 Chapter 7 Classes Part II Outline 7

  • Slides: 31
Download presentation
1 Chapter 7: Classes Part II Outline 7. 1 7. 2 7. 3 7.

1 Chapter 7: Classes Part II Outline 7. 1 7. 2 7. 3 7. 4 7. 5 7. 6 7. 7 7. 8 7. 9 7. 10 Introduction const (Constant) Objects and const Member Functions Composition: Objects as Members of Classes friend Functions and friend Classes Using the this Pointer Dynamic Memory Management with Operators new and delete static Class Members Data Abstraction and Information Hiding 7. 8. 1 Example: Array Abstract Data Type 7. 8. 2 Example: String Abstract Data Type 7. 8. 3 Example: Queue Abstract Data Type Container Classes and Iterators Proxy Classes 2003 Prentice Hall, Inc. All rights reserved.

2 7. 1 Introduction • Classes • Data abstraction • Object-based programming (OBP) –

2 7. 1 Introduction • Classes • Data abstraction • Object-based programming (OBP) – Chapters 6 -8 • Inheritance and polymorphism – Chapters 9 and 10 2003 Prentice Hall, Inc. All rights reserved.

7. 2 const (Constant) Objects and const Member Functions • Principle of least privilege

7. 2 const (Constant) Objects and const Member Functions • Principle of least privilege – Only allow modification of necessary objects • Keyword const – Specify object not modifiable – Compiler error if attempt to modify const object – Example const Time noon( 12, 0, 0 ); • Declares const object noon of class Time • Initializes to 12 2003 Prentice Hall, Inc. All rights reserved. 3

7. 2 const (Constant) Objects and const Member Functions • const member functions –

7. 2 const (Constant) Objects and const Member Functions • const member functions – Member functions for const objects must also be const • Cannot modify object – Specify const in both prototype and definition • Prototype – After parameter list • Definition – Before beginning left brace 2003 Prentice Hall, Inc. All rights reserved. 4

7. 2 const (Constant) Objects and const Member Functions • Constructors and destructors –

7. 2 const (Constant) Objects and const Member Functions • Constructors and destructors – Cannot be const – Must be able to modify objects • Constructor – Initializes objects • Destructor – Performs termination housekeeping 2003 Prentice Hall, Inc. All rights reserved. 5

1 2 3 4 5 // Fig. 7. 1: time 5. h // Definition

1 2 3 4 5 // Fig. 7. 1: time 5. h // Definition of class Time. // Member functions defined in time 5. cpp. #ifndef TIME 5_H #define TIME 5_H 6 7 class Time { 8 9 10 public: Time( int = 0, int = 0 ); Outline time 5. h (1 of 2) // default constructor 11 12 13 14 15 16 // set functions void set. Time( int, int ); void set. Hour( int ); void set. Minute( int ); void set. Second( int ); 17 18 19 20 21 // get functions (normally declared const) int get. Hour() const; // return hour int get. Minute() const; // return minute int get. Second() const; // return second 22 23 24 25 // print functions (normally declared const) void print. Universal() const; // print universal time void print. Standard(); // print standard time // // set set time hour minute second Declare const get functions. Declare const function print. Universal. 2003 Prentice Hall, Inc. All rights reserved. 6

26 27 28 29 30 private: int hour; int minute; int second; 31 32

26 27 28 29 30 private: int hour; int minute; int second; 31 32 }; // end class Time 33 34 #endif Outline // 0 - 23 (24 -hour clock format) // 0 - 59 time 5. h (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 7

1 2 3 // Fig. 7. 2: time 5. cpp // Member-function definitions for

1 2 3 // Fig. 7. 2: time 5. cpp // Member-function definitions for class Time. #include <iostream> 4 5 using std: : cout; 6 7 #include <iomanip> 8 9 10 using std: : setfill; using std: : setw; 11 12 13 // include definition of class Time from time 5. h #include "time 5. h" 14 15 16 17 18 19 20 // constructor function to initialize private data; // calls member function set. Time to set variables; // default values are 0 (see class definition) Time: : Time( int hour, int minute, int second ) { set. Time( hour, minute, second ); 21 22 } // end Time constructor Outline time 5. cpp (1 of 4) 23 2003 Prentice Hall, Inc. All rights reserved. 8

24 25 26 27 28 29 // set hour, minute and second values void

24 25 26 27 28 29 // set hour, minute and second values void Time: : set. Time( int hour, int minute, int second ) { set. Hour( hour ); set. Minute( minute ); set. Second( second ); 30 31 } // end function set. Time 32 33 34 35 36 // set hour value void Time: : set. Hour( int h ) { hour = ( h >= 0 && h < 24 ) ? h : 0; 37 38 } // end function set. Hour 39 40 41 42 43 // set minute value void Time: : set. Minute( int m ) { minute = ( m >= 0 && m < 60 ) ? m : 0; 44 45 } // end function set. Minute Outline time 5. cpp (2 of 4) 46 2003 Prentice Hall, Inc. All rights reserved. 9

47 48 49 50 // set second value void Time: : set. Second( int

47 48 49 50 // set second value void Time: : set. Second( int s ) { second = ( s >= 0 && s < 60 ) ? s : 0; 51 52 } // end function set. Second 53 54 55 56 57 // return hour value int Time: : get. Hour() const { return hour; 58 59 } // end function get. Hour 60 61 62 63 64 // return minute value int Time: : get. Minute() const { return minute; 65 66 } // end function get. Minute Outline time 5. cpp (3 of 4) const functions do not modify objects. 67 2003 Prentice Hall, Inc. All rights reserved. 10

68 69 70 71 72 73 // return second value int Time: : get.

68 69 70 71 72 73 // return second value int Time: : get. Second() const { return second; } // end function get. Second Outline time 5. cpp (4 of 4) const functions do not modify objects. 74 75 76 77 78 79 80 // print Time in universal format void Time: : print. Universal() const { cout << setfill( '0' ) << setw( 2 ) << hour << ": " << setw( 2 ) << minute << ": " << setw( 2 ) << second; 81 82 } // end function print. Universal 83 84 85 86 87 88 89 90 // print Time in standard format void Time: : print. Standard() // note lack of const declaration { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ": " << setfill( '0' ) << setw( 2 ) << minute << ": " << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 91 92 } // end function print. Standard 2003 Prentice Hall, Inc. All rights reserved. 11

1 2 3 // Fig. 7. 3: fig 07_03. cpp // Attempting to access

1 2 3 // Fig. 7. 3: fig 07_03. cpp // Attempting to access a const object with // non-const member functions. 4 5 6 // include Time class definition from time 5. h #include "time 5. h" 7 8 9 10 11 int main() { Time wake. Up( 6, 45, 0 ); const Time noon( 12, 0, 0 ); Outline fig 07_03. cpp (1 of 2) Declare noon a const object. // non-constant object // constant object 12 Note that non-constructor can initialize const object. 2003 Prentice Hall, Inc. All rights reserved. 12

13 14 wake. Up. set. Hour( 18 ); // OBJECT // non-const MEMBER FUNCTION

13 14 wake. Up. set. Hour( 18 ); // OBJECT // non-const MEMBER FUNCTION non-const 15 16 noon. set. Hour( 12 ); // const non-const 17 18 wake. Up. get. Hour(); // non-const 19 20 21 noon. get. Minute(); // const noon. print. Universal(); // const 22 23 noon. print. Standard(); 24 25 return 0; // const Attempting to invoke nonmember function on const object results in compiler error. non-const Outline fig 07_03. cpp (2 of 2) fig 07_03. cpp output (1 of 1) Attempting to invoke non} // end main const member function on const object results in d: cpphtp 4_examplesch 07fig 07_01. cpp(16) : error C 2662: compiler error even if 'set. Hour' : cannot convert 'this' pointer from 'const class Time' function does not modify to 'class Time &' object. Conversion loses qualifiers 26 27 d: cpphtp 4_examplesch 07fig 07_01. cpp(23) : error C 2662: 'print. Standard' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers 2003 Prentice Hall, Inc. All rights reserved. 13

7. 2 const (Constant) Objects and const Member Functions • Member initializer syntax –

7. 2 const (Constant) Objects and const Member Functions • Member initializer syntax – Initializing with member initializer syntax • Can be used for – All data members • Must be used for – const data members – Data members that are references 2003 Prentice Hall, Inc. All rights reserved. 14

1 2 3 4 // Fig. 7. 4: fig 07_04. cpp // Using a

1 2 3 4 // Fig. 7. 4: fig 07_04. cpp // Using a member initializer to initialize a // constant of a built-in data type. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 class Increment { 10 11 12 public: Increment( int c = 0, int i = 1 ); 13 14 15 16 void add. Increment() { count += increment; 17 18 } // end function add. Increment 19 20 void print() const; Outline fig 07_04. cpp (1 of 3) // default constructor // prints count and increment 21 2003 Prentice Hall, Inc. All rights reserved. 15

22 23 24 private: int count; const increment; 25 26 }; // end class

22 23 24 private: int count; const increment; 25 26 }; // end class Increment 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 Outline // const data member Member initializer list Declare increment as const separated from parameter datalist member. // constructor Member initializer syntax can Increment: : Increment(byint c, int i ) colon. be used for non-const data Member initializermember syntax : count( c ), // initializer for non-const member must count. be used for const data increment( i ) fig 07_04. cpp (2 of 3) // required initializer for const member { member increment. // empty body Member initializer consists of data member name (increment) followed by // print count and increment values void Increment: : print() const parentheses containing initial { value (c). } // end Increment constructor cout << "count = " << count << ", increment = " << increment << endl; } // end function print 44 2003 Prentice Hall, Inc. All rights reserved. 16

45 46 47 int main() { Increment value( 10, 5 ); Outline 48 49

45 46 47 int main() { Increment value( 10, 5 ); Outline 48 49 50 cout << "Before incrementing: "; value. print(); 51 52 53 54 55 56 for ( int j = 0; j < 3; j++ ) { value. add. Increment(); cout << "After increment " << j + 1 << ": "; value. print(); } 57 58 return 0; 59 60 fig 07_04. cpp (3 of 3) fig 07_04. cpp output (1 of 1) } // end main Before incrementing: count After increment 1: count = After increment 2: count = After increment 3: count = = 10, increment 15, increment = 20, increment = 25, increment = = 5 5 2003 Prentice Hall, Inc. All rights reserved. 17

1 2 3 4 // Fig. 7. 5: fig 07_05. cpp // Attempting to

1 2 3 4 // Fig. 7. 5: fig 07_05. cpp // Attempting to initialize a constant of // a built-in data type with an assignment. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 class Increment { 10 11 12 public: Increment( int c = 0, int i = 1 ); 13 14 15 16 void add. Increment() { count += increment; 17 18 } // end function add. Increment 19 20 void print() const; Outline fig 07_05. cpp (1 of 3) // default constructor // prints count and increment 21 2003 Prentice Hall, Inc. All rights reserved. 18

22 23 24 private: int count; const increment; 25 26 }; // end class

22 23 24 private: int count; const increment; 25 26 }; // end class Increment 27 28 29 30 31 32 33 34 Outline // const data member Declare increment as const data member. // constructor Attempting to modify const Increment: : Increment( int c, int i ) data memberisincrement { // Constant member 'increment' not initialized count = c; // allowed because count is not constant results in error. increment = i; fig 07_05. cpp (2 of 3) // ERROR: Cannot modify a const object } // end Increment constructor 35 36 37 38 39 40 // print count and increment values void Increment: : print() const { cout << "count = " << count << ", increment = " << increment << endl; 41 42 } // end function print 43 2003 Prentice Hall, Inc. All rights reserved. 19

44 45 46 int main() { Increment value( 10, 5 ); Outline 47 48

44 45 46 int main() { Increment value( 10, 5 ); Outline 47 48 49 cout << "Before incrementing: "; value. print(); 50 51 52 53 54 55 for ( int j = 0; j < 3; j++ ) { value. add. Increment(); cout << "After increment " << j + 1 << ": "; value. print(); } 56 57 return 0; 58 59 } // end main fig 07_05. cpp (3 of 3) fig 07_05. cpp output (1 of 1) Not using member initializer syntax to initialize const data member increment results in error. D: cpphtp 4_examplesch 07Fig 07_03. cpp(30) : error C 2758: 'increment' : must be initialized in constructor base/member Attempting to modify const initializer list data member increment D: cpphtp 4_examplesch 07Fig 07_03. cpp(24) : results in error. see declaration of 'increment' D: cpphtp 4_examplesch 07Fig 07_03. cpp(32) : error C 2166: l-value specifies const object 2003 Prentice Hall, Inc. All rights reserved. 20

7. 3 Composition: Objects as Members of Classes • Composition – Class has objects

7. 3 Composition: Objects as Members of Classes • Composition – Class has objects of other classes as members • Construction of objects – Member objects constructed in order declared • Not in order of constructor’s member initializer list • Constructed before enclosing class objects (host objects) 2003 Prentice Hall, Inc. All rights reserved. 21

1 2 3 4 5 // Fig. 7. 6: date 1. h // Date

1 2 3 4 5 // Fig. 7. 6: date 1. h // Date class definition. // Member functions defined in date 1. cpp #ifndef DATE 1_H #define DATE 1_H 6 7 class Date { 8 9 10 11 12 public: Date( int = 1, int = void print() const; // print ~Date(); // provided to confirm destruction order 13 14 15 16 17 private: int month; int day; int year; 18 19 20 Outline date 1. h (1 of 1) Note no constructor with parameter of type Date. Recall provides 1900 ); compiler // default constructor default copy constructor. format date in month/day/year // 1 -12 (January-December) // 1 -31 based on month // any year // utility function to test proper day for month and year int check. Day( int ) const; 21 22 }; // end class Date 23 24 #endif 2003 Prentice Hall, Inc. All rights reserved. 22

1 2 3 // Fig. 7. 7: date 1. cpp // Member-function definitions for

1 2 3 // Fig. 7. 7: date 1. cpp // Member-function definitions for class Date. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 // include Date class definition from date 1. h #include "date 1. h" 10 11 12 13 14 15 16 // constructor confirms proper value for month; calls // utility function check. Day to confirm proper value for day Date: : Date( int mn, int dy, int yr ) { if ( mn > 0 && mn <= 12 ) // validate the month = mn; Outline date 1. cpp (1 of 3) 17 18 19 20 21 else { // invalid month set to 1 month = 1; cout << "Month " << mn << " invalid. Set to month 1. n" ; } 22 23 24 year = yr; day = check. Day( dy ); // should validate yr // validate the day 25 2003 Prentice Hall, Inc. All rights reserved. 23

26 27 28 29 // output Date object to show when its constructor is

26 27 28 29 // output Date object to show when its constructor is called cout << "Date object constructor for date " ; print(); cout << endl; 30 31 } // end Date constructor 32 33 34 35 36 // print Date object in form void Date: : print() const { cout << month << '/' << day << '/' << year; 37 38 } // end function print 39 40 41 42 43 44 45 46 47 Outline date 1. cpp (2 of 3) No arguments; each member Output to show timing of function contains implicit constructors. handle to object on which it month/day/year operates. to show // output Date object to show when its. Output destructor is timing calledof Date: : ~Date() destructors. { cout << "Date object destructor for date " ; print(); cout << endl; } // end destructor ~Date 48 2003 Prentice Hall, Inc. All rights reserved. 24

49 50 51 52 53 54 // utility function to confirm proper day value

49 50 51 52 53 54 // utility function to confirm proper day value based on // month and year; handles leap years, too int Date: : check. Day( int test. Day ) const { static const int days. Per. Month[ 13 ] = { 0, 31, 28, 31, 30, 31 }; 55 56 57 58 // determine whether test. Day is valid for specified month if ( test. Day > 0 && test. Day <= days. Per. Month[ month ] ) return test. Day; 59 60 61 62 63 64 // February 29 check for leap year if ( month == 2 && test. Day == 29 && ( year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) return test. Day; 65 66 cout << "Day " << test. Day << " invalid. Set to day 1. n" ; 67 68 return 1; 69 70 Outline date 1. cpp (3 of 3) // leave object in consistent state if bad value } // end function check. Day 2003 Prentice Hall, Inc. All rights reserved. 25

1 2 3 4 5 // Fig. 7. 8: employee 1. h // Employee

1 2 3 4 5 // Fig. 7. 8: employee 1. h // Employee class definition. // Member functions defined in employee 1. cpp. #ifndef EMPLOYEE 1_H #define EMPLOYEE 1_H 6 7 8 // include Date class definition from date 1. h #include "date 1. h" 9 10 class Employee { 11 12 13 14 public: Employee( const char *, const Date &, const Date & ); 15 16 17 void print() const; ~Employee(); // provided to confirm destruction order 18 19 20 21 22 23 private: char first. Name[ 25 ]; char last. Name[ 25 ]; const Date birth. Date; const Date hire. Date; 24 25 }; // end class Employee // composition: member object Outline 26 employee 1. h (1 of 2) Using composition; Employee object contains Date objects as data members. 2003 Prentice Hall, Inc. All rights reserved.

26 27 Outline #endif 27 employee 1. h (2 of 2) 1 2 3

26 27 Outline #endif 27 employee 1. h (2 of 2) 1 2 3 // Fig. 7. 9: employee 1. cpp // Member-function definitions for class Employee. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <cstring> // strcpy and strlen prototypes 9 10 11 #include "employee 1. h" #include "date 1. h" // Employee class definition // Date class definition employee 1. cpp (1 of 3) 12 2003 Prentice Hall, Inc. All rights reserved.

13 14 15 16 17 18 19 20 21 22 23 24 25 26

13 14 15 16 17 18 19 20 21 22 23 24 25 26 // constructor uses member initializer list to pass initializer // values to constructors of member objects birth. Date and // hire. Date [Note: This invokes the so-called "default copy // constructor" which the C++ compiler provides implicitly. ] Employee: : Employee( const char *first, const char *last, const Date &date. Of. Birth, const Date &date. Of. Hire ) : birth. Date( date. Of. Birth ), // initialize birth. Date hire. Date( date. Of. Hire ) // initialize hire. Date { syntax to // copy first into first. Name and be sure Member that it initializer fits initialize Date data members int length = strlen( first ); length = ( length < 25 ? length : 24 ); birth. Date and hire. Date; compiler uses strncpy( first. Name, first, length ); first. Name[ length ] = ''; default copy constructor. 27 28 29 30 31 32 // copy last into last. Name and be sure that it fits length = strlen( last ); length = ( length < 25 ? length : 24 ); strncpy( last. Name, last, length ); last. Name[ length ] = ''; Output to show 33 34 35 36 // output Employee object to show when constructor is called cout << "Employee object constructor: " << first. Name << ' ' << last. Name << endl; Outline employee 1. cpp (2 of 3) timing of constructors. 37 2003 Prentice Hall, Inc. All rights reserved. 28

38 } // end Employee constructor 39 40 41 42 43 44 45 46

38 } // end Employee constructor 39 40 41 42 43 44 45 46 47 // print Employee object void Employee: : print() const { cout << last. Name << ", " << first. Name << "n. Hired: "; hire. Date. print(); cout << " Birth date: "; birth. Date. print(); cout << endl; 48 49 } // end function print 50 51 52 53 54 55 56 57 Outline employee 1. cpp (3 of 3) to show // output Employee object to show when its Output destructor is timing calledof destructors. Employee: : ~Employee() { cout << "Employee object destructor: " << last. Name << ", " << first. Name << endl; } // end destructor ~Employee 2003 Prentice Hall, Inc. All rights reserved. 29

1 2 3 // Fig. 7. 10: fig 07_10. cpp // Demonstrating composition--an object

1 2 3 // Fig. 7. 10: fig 07_10. cpp // Demonstrating composition--an object with member objects. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include "employee 1. h" 9 10 11 12 13 14 Create Date objects to pass int main() { to Employee constructor. Date birth( 7, 24, 1949 ); Date hire( 3, 12, 1988 ); Employee manager( "Bob", "Jones", birth, hire ); fig 07_10. cpp (1 of 1) // Employee class definition 15 16 17 cout << 'n'; manager. print(); 18 19 20 21 cout << "n. Test Date constructor with invalid values: n" ; Date last. Day. Off( 14, 35, 1994 ); // invalid month and day cout << endl; 22 23 return 0; 24 25 Outline } // end main 2003 Prentice Hall, Inc. All rights reserved. 30

Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Employee object

Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Employee object constructor: Bob Jones, Bob Hired: 3/12/1988 Birth date: 7/24/1949 Test Date constructor with invalid values: Month 14 invalid. Set to month 1. Day 35 invalid. Set to day 1. Date object constructor for date 1/1/1994 Date object destructor for date 1/1/1994 Employee object destructor: Jones, Bob Date object destructor for date 3/12/1988 Date object destructor for date 7/24/1949 Outline Note two additional Datefig 07_10. cpp objects constructed; no output (1 of 1) since default copy constructor used. Destructor for host object Destructor Employee’s manager runsfor before member object hire. Date. Destructor Employee‘s destructors for member Destructor for Date member object birth. Date. objects hire. Date and object Destructor for Date object hire. birth. Date. birth. 2003 Prentice Hall, Inc. All rights reserved. 31