1 Chapter 7 Classes Part II Outline 7

  • Slides: 69
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.

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. 2

7. 2 const (Constant) Objects and const Member Functions • const objects require const

7. 2 const (Constant) Objects and const Member Functions • const objects require const functions – Member functions declared const cannot modify their object – const must be specified in function prototype and definition • Prototype (after parameter list): Return. Type Function. Name(param 1, param 2…) const; • Definition (before left brace): Return. Type Function. Name(param 1, param 2…) const { …} • Example: int A: : get. Value() const { return private. Data. Member }; • Returns the value of a data member but doesn’t modify anything so is declared const • Constructors / Destructors cannot be const – They need to initialize variables, therefore modifying them 2003 Prentice Hall, Inc. All rights reserved. 3

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Fig. 7. 1: time 5. h // Declaration of the class Time. // Member functions defined in time 5. cpp #ifndef TIME 5_H #define TIME 5_H Outline class Time { public: Time( int = 0, int = 0 ); // default constructor // set functions void set. Time( int, int ); // set time void set. Hour( int ); // set hour void set. Minute( int ); // set minute void set. Second( int ); // set second // get functions (normally declared const) int get. Hour() const; // return hour int get. Minute() const; // return minute int get. Second() const; // return second // print functions (normally declared const) void print. Military() const; // print military timeconst void print. Standard(); // print standard timefunctions private: int hour; // 0 - 23 int minute; // 0 - 59 non-const int second; // 0 - 59 functions }; #endif 2003 Prentice Hall, Inc. All rights reserved. 4

32 33 34 36 37 38 39 40 41 42 43 44 45 46

32 33 34 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 // Fig. 7. 1: time 5. cpp // Member function definitions for Time class. #include <iostream> using std: : cout; The constructor is non-const but Outline it can be called for const objects. #include "time 5. h" // Constructor function to initialize private data. // Default values are 0 (see class definition). Time: : Time( int hr, int min, int sec ) { set. Time( hr, min, sec ); } // Set the values of hour, minute, and second. void Time: : set. Time( int h, int m, int s ) { set. Hour( h ); set. Minute( m ); set. Second( s ); } // Set the hour value void Time: : set. Hour( int h ) { hour = ( h >= 0 && h < 24 ) ? h : 0; } // Set the minute value void Time: : set. Minute( int m ) { minute = ( m >= 0 && m < 60 ) ? m : 0; } // Set the second value void Time: : set. Second( int s ) { second = ( s >= 0 && s < 60 ) ? s : 0; } 2003 Prentice Hall, Inc. All rights reserved. 5

64 Outline 65 // Get the hour value 66 int Time: : get. Hour()

64 Outline 65 // Get the hour value 66 int Time: : get. Hour() const { return hour; } 67 68 // Get the minute value Keyword const in function definition and prototype. 69 int Time: : get. Minute() const { return minute; } 70 71 // Get the second value 72 int Time: : get. Second() const { return second; } 73 74 // Display military format time: HH: MM 75 void Time: : print. Military() const 76 77 78 Non-const functions cannot use { const objects, even if they don’t cout << ( hour < 10 ? "0" : "" ) << hour << ": " modify them (such as << ( minute < 10 ? "0" : "" ) << minute; print. Standard). 79 } 80 81 // Display standard format time: HH: MM: SS AM (or PM) 82 void Time: : print. Standard() // should be const 83 { 84 cout << ( ( hour == 12 ) ? 12 : hour % 12 ) << ": " 85 << ( minute < 10 ? "0" : "" ) << minute << ": " 86 << ( second < 10 ? "0" : "" ) << second 87 << ( hour < 12 ? " AM" : " PM" ); 2003 Prentice Hall, Inc. 88 } All rights reserved. 6

89 // Fig. 7. 1: fig 07_01. cpp 90 // Attempting to access a

89 // Fig. 7. 1: fig 07_01. cpp 90 // Attempting to access a const object with 91 // non-const member functions. 92 #include "time 5. h" 93 94 int main() 95 { 96 Time wake. Up( 6, 45, 0 ); // non-constant object 97 const Time noon( 12, 0, 0 ); // constant object 98 99 // MEMBER FUNCTION OBJECT 100 wake. Up. set. Hour( 18 ); // non-const 101 102 noon. set. Hour( 12 ); // non-const const 103 104 wake. Up. get. Hour(); // const non-const 105 106 noon. get. Minute(); // const 107 noon. print. Military(); // const 108 noon. print. Standard(); // non-const const 109 return 0; Compiler 110 } Compiling. . . Fig 07_01. cpp d: fig 07_01. cpp(14) : error C 2662: 'set. Hour' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers d: fig 07_01. cpp(20) : error C 2662: 'print. Standard' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers Time 5. cpp Error executing cl. exe. test. exe - 2 error(s), 0 warning(s) Outline errors generated. 2003 Prentice Hall, Inc. All rights reserved. 7

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

7. 2 const (Constant) Objects and const Member Functions • Member initializer syntax – Data member const increment in class Increment – constructor for Increment is modified as follows: Increment: : Increment( int c, int i ) : count( c ), increment( i ) {/* empty body */ } – : increment( i ) initializes increment to i – Multiple member initializers: • Use comma-separated list after the colon – Can be used for • All data members – Must be used for: • consts and references • Member objects, base class portion (later) 2003 Prentice Hall, Inc. All rights reserved. 8

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Fig. 7. 2: fig 07_02. cpp Declare increment // Using a member initializer to initialize a // constant of a built-in data type. data member. #include <iostream> as const Member initializer consists of data member name (increment) followed by parentheses containing initial value (c). Initialization is executed before body of constructor using std: : cout; using std: : endl; class Increment { public: Increment( int c = 0, int i = 1 ); void add. Increment() { count += increment; } void print() const; private: int count; const increment; // const data member }; Outline Member initializer syntax must be used for const data member increment. Member initializer syntax can data // Constructor for class Increment be used for non-const Increment: : Increment( int c, int i ) member count. : increment( i ), count( c ) // initializer for const member { /* empty body */ } // Print the data void Increment: : print() const { cout << "count = " << count << ", increment = " << increment << endl; } If we try to initialize increment with an assignment statement (such as increment = i ) instead of a member initializer we get an error. 2003 Prentice Hall, Inc. All rights reserved. 9

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

45 46 47 int main() { Increment value( 10, 5 ); 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 } // end main Outline fig 07_04. cpp (3 of 3) fig 07_04. cpp output (1 of 1) Before incrementing: count = 10, increment = 5 After increment 1: count = 15, increment = 5 After increment 2: count = 20, increment = 5 After increment 3: count = 25, increment = 5 2003 Prentice Hall, Inc. All rights reserved. 10

Compiler Errors when not Initializing Properly 22 23 24 private: int count; const increment;

Compiler Errors when not Initializing Properly 22 23 24 private: int count; const increment; // const data member 25 26 }; // end class Increment 27 28 29 30 31 32 33 34 Declare increment as const data member. // constructor Attempting to modify const Increment: : Increment( int c, int i ) data member increment { // Constant member 'increment' is not initialized count = c; // allowed because count is not constant results in error. Outline fig 07_05. cpp (2 of 3) increment = i; // ERROR: Cannot modify a const object Not using member initializer } // end Increment constructor 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. 11

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) – From the Inside Out • Destruction of objects – Member objects destroyed in inverse order of their creation – From Outside In 2003 Prentice Hall, Inc. All rights reserved. 12

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 Outline Note no constructor with a parameter of type Date. public: Date( int = 1, int = 1900 ); // default constructor Recall compiler provides void print() const; // print date in month/day/year format default copy constructor. ~Date(); // provided to confirm destruction order 13 14 15 16 17 private: int month; // 1 -12 (January-December) int day; // 1 -31 based on month int year; // any year 18 19 20 // utility function to test proper day for month and year int check. Day( int ) const; 21 22 }; // end class Date 23 24 #endif date 1. h (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 13

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; 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; // should validate yr day = check. Day( dy ); // validate the day Outline date 1. cpp (1 of 3) 25 2003 Prentice Hall, Inc. All rights reserved. 14

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 { cout << month << '/' << day << '/' << year; Outline No arguments; each member Output to show timing of function contains implicit constructors. handle to object on which it // print Date object in form month/day/year operates. void Date: : print() const 37 38 } // end function print 39 40 41 42 43 44 45 46 47 Output to show timing of // output Date object to show when its destructor is called Date: : ~Date() destructors. { cout << "Date object destructor for date " ; print(); cout << endl; } // end destructor ~Date date 1. cpp (2 of 3) 48 2003 Prentice Hall, Inc. All rights reserved. 15

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; // leave object in consistent state if bad value 69 70 } // end function check. Day Outline date 1. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 16

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; // composition: member object const Date hire. Date; // composition: member object 24 25 }; // end class Employee Outline 17 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 #endif 1 2 3 // Fig. 7. 9: employee 1. cpp //

26 27 #endif 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" // Employee class definition #include "date 1. h" // Date class definition Outline 18 employee 1. h (2 of 2) 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 { Member initializer syntax to // copy first into first. Name and be sure that it 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. 19

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 Output to show timing of // output Employee object to show when its destructor is called destructors. Employee: : ~Employee() Outline employee 1. cpp (3 of 3) { cout << "Employee object destructor: " << last. Name << ", " << first. Name << endl; } // end destructor ~Employee 2003 Prentice Hall, Inc. All rights reserved. 20

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" // Employee class definition 9 10 11 12 13 14 Create Date objects to pass int main() { to Employee constructor, Date birth( 7, 24, 1949 ); creation causes user defined Date hire( 3, 12, 1988 ); constructor to be called. Employee manager( "Bob", "Jones", birth, hire ); 15 16 17 cout << 'n'; manager. print(); 18 19 20 21 Date last. Day. Off( 14, 35, 1994 ); // invalid month and day cout << endl; Outline fig 07_10. cpp (1 of 1) Birth and hire causes an additonal constructor to be cout << "n. Test Date constructor with invalid values: n" ; (which one? ) called 22 23 return 0; 24 25 } // end main 2003 Prentice Hall, Inc. All rights reserved. 21

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 Date objects constructed; no output since default copy constructor used. Destructor for host object Destructor for Employee’s manager runs beforefig 07_10. cpp Destructor for member object hire. Date. destructors for Employee‘s member output (1 of 1) Destructor for Date object member object birth. Date. objects hire. Date and Destructor for Date object hire (created in birth. Date. birth main). -recall destruction - outside in 2003 Prentice Hall, Inc. All rights reserved. 22

23 7. 4 friend Functions and friend Classes • friend function and friend classes

23 7. 4 friend Functions and friend Classes • friend function and friend classes – Can access non-public members of a class: private and protected members of another class – friend functions are not member functions of class • Defined outside of class scope • Declaring friends – To declare a friend function • Type friend before the function prototype in the class that is giving friendship friend int my. Function( int x ); should appear in the class giving friendship – To declare a friend class • Type friend class Classname in the class that is giving friendship • if Class. One is granting friendship to Class. Two, friend class Class. Two; – should appear in Class. One's definition 2003 Prentice Hall, Inc. All rights reserved.

24 7. 4 friend Functions and friend Classes • Properties of friendship – Friendship

24 7. 4 friend Functions and friend Classes • Properties of friendship – Friendship granted, not taken • Class B friend of class A – Class A must explicitly declare class B friend – Not symmetric (not mutual) • Class B friend of class A • Class A not necessarily friend of class B – Not transitive • Class A friend of class B • Class B friend of class C • Class A not necessarily friend of Class C 2003 Prentice Hall, Inc. All rights reserved.

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

1 // Fig. 7. 5: fig 07_05. cpp 2 3 4 5 6 // Friends can access private members of a class. #include <iostream> using std: : cout; using std: : endl; 7 8 9 Outline set. X a friend of class Count (can access private data). Convention: Declare friends first. // Modified Count class Count { 10 friend void set. X( Count &, int ); // friend declaration 11 public: 12 Count() { x = 0; } // constructor 13 void print() const { cout << x << endl; } // output set. X is defined 14 private: 15 int x; // data member 16 }; 17 18 // Can modify private data of Count because normally and is not a member function of Count. Handle to count is passed in via c. 19 // set. X is declared as a friend function of Count Changing private 20 void set. X( Count &c, int val ) 21 22 23 24 25 26 variables allowed. { c. x = val; // legal: set. X is a friend of Count } int main() { 27 Count counter; 28 29 cout << "counter. x after instantiation: "; 30 counter. print(); 2003 Prentice Hall, Inc. All rights reserved. 25

31 cout << "counter. x after call to set. X friend function: "; 32

31 cout << "counter. x after call to set. X friend function: "; 32 set. X( counter, 8 ); // set x with a friend Outline 33 counter. print(); 34 return 0; 35 } Use friend function to access and modify private member x counter. x after instantiation: 0 counter. x after call to set. X friend function: 8 private data was changed. 2003 Prentice Hall, Inc. All rights reserved. 26

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Fig. 7. 6: fig 07_06. cpp // Non-friend/non-member functions cannot access // private data of a class. #include <iostream> using std: : cout; using std: : endl; Outline cannot. Set. X is not a friend of class Count. It cannot access private data. // Modified Count class Count { public: Count() { x = 0; } // constructor void print() const { cout << x << endl; } // output private: int x; // data member }; // Function tries to modify private data of Count, // but cannot because it is not a friend of Count. void cannot. Set. X( Count &c, int val ) { c. x = val; // ERROR: 'Count: : x' is not accessible } int main() { Count counter; cannot. Set. X tries to modify a private variable… cannot. Set. X( counter, 3 ); // cannot. Set. X is not a friend return 0; } 2003 Prentice Hall, Inc. All rights reserved. 27

 Compiling. . . Fig 07_06. cpp D: books2000cpphtp 3examplesCh 07Fig 07_06. cpp(22) :

Compiling. . . Fig 07_06. cpp D: books2000cpphtp 3examplesCh 07Fig 07_06. cpp(22) : error C 2248: 'x' : cannot access private member declared in class 'Count' D: books2000cpphtp 3examplesCh 07Fig 07_06 Fig 07_06. cpp(15) : see declaration of 'x' Error executing cl. exe. test. exe - 1 error(s), 0 warning(s) Outline Expected compiler error - cannot access private data 2003 Prentice Hall, Inc. All rights reserved. 28

29 7. 5 Using the this Pointer • this pointer – Allows object to

29 7. 5 Using the this Pointer • this pointer – Allows object to access own address – Not part of object itself • Implicit argument to non-static member function call – Implicitly reference member data and functions – Type of this pointer depends on • Type of object • Whether member function is const • In non-const member function of Employee – this has type Employee * const • Constant pointer to non-constant Employee object • In const member function of Employee – this has type const Employee * const • Constant pointer to constant Employee object 2003 Prentice Hall, Inc. All rights reserved.

30 7. 5 Using the this Pointer • Examples using this – For a

30 7. 5 Using the this Pointer • Examples using this – For a member function print data member x, either this->x or ( *this ). x – Need parenthesis, without *this. x would be evaluated as *(this. x), because ”. ” precedence, however cannot use the dot operator with a pointer. • A use of this pointer is to prevent self assigment (i. e. an object assigned to itself) -- later 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 // Fig. 7. 13: fig 07_13. cpp // Using the this

1 2 3 // Fig. 7. 13: fig 07_13. cpp // Using the this pointer to refer to object members. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 class Test { 9 10 11 12 public: Test( int = 0 ); // default constructor void print() const; 13 14 15 private: int x; 16 17 }; // end class Test 18 19 20 21 22 23 24 25 // constructor Test: : Test( int value ) : x( value ) // initialize x to value { // empty body } // end Test constructor Outline fig 07_13. cpp (1 of 3) 2003 Prentice Hall, Inc. All rights reserved. 31

26 27 28 29 30 31 32 // print x using implicit and explicit

26 27 28 29 30 31 32 // print x using implicit and explicit this pointers; // parentheses around *this required Implicitly use this pointer; void Test: : print() const only specify name of data { member (x). // implicitly use this pointer to access member x Explicitly use this pointer cout << " x = " << x; 33 34 35 36 37 38 39 // explicitly use this pointer to access member x cout << "n this->x = " << this->x; Explicitly use this pointer; dereference this pointer // explicitly use dereferenced this pointer and fig 07_13. cpp // the dot operator to access member x first, then use dot operator. cout << "n(*this). x = " << ( * this ). x << endl; (2 of 3) 40 41 } // end function print 42 43 44 45 int main() { Test test. Object( 12 ); 46 47 test. Object. print(); 48 49 return 0; Outline with arrow operator. 50 2003 Prentice Hall, Inc. All rights reserved. 32

51 } // end main Outline x = 12 this->x = 12 (*this). x

51 } // end main Outline x = 12 this->x = 12 (*this). x = 12 fig 07_13. cpp (3 of 3) fig 07_13. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 33

34 7. 5 Using the this Pointer • Cascaded member function calls – Multiple

34 7. 5 Using the this Pointer • Cascaded member function calls – Multiple functions invoked in same statement – Function returns a reference pointer to same object { return *this; } – Other functions operate on that pointer – Functions that do not return references must be called last – Idea dot operator (. ) associates from left to right : t. set. Hour( 18 ). set. Minute( 30 ). set. Second( 22 ); each statement returns a reference to object t as the value of the function call 2003 Prentice Hall, Inc. All rights reserved.

1 2 // Fig. 7. 14: time 6. h // Cascading member function calls.

1 2 // Fig. 7. 14: time 6. h // Cascading member function calls. 3 4 5 6 7 // Time class definition. // Member functions defined in time 6. cpp. #ifndef TIME 6_H #define TIME 6_H 8 9 class Time { 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Outline public: Set functions return reference Time( int = 0, int = 0 ); // default constructor to Time object to enable cascaded member function // set functions calls. Time &set. Time( int, int ); // set hour, minute, second Time &set. Hour( int ); // set hour Time &set. Minute( int ); // set minute Time &set. Second( int ); // set second time 6. h (1 of 2) // get functions (normally declared const) int get. Hour() const; // return hour int get. Minute() const; // return minute int get. Second() const; // return second 24 2003 Prentice Hall, Inc. All rights reserved. 35

25 26 27 // print functions (normally declared const) void print. Universal() const; //

25 26 27 // print functions (normally declared const) void print. Universal() const; // print universal time void print. Standard() const; // print standard time 28 29 30 31 32 private: int hour; // 0 - 23 (24 -hour clock format) int minute; // 0 - 59 int second; // 0 - 59 33 34 }; // end class Time 35 36 #endif Outline time 6. h (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 36

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

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

23 24 25 26 27 28 29 30 31 32 33 34 35 36

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 // set values of hour, minute, and second Time &Time: : set. Time( int h, int m, int s ) { set. Hour( h ); set. Minute( m ); Return *this as reference set. Second( s ); enable cascaded member Outline to function calls. return *this; // enables cascading } // end function set. Time // set hour value Time &Time: : set. Hour( int h ) { Return *this as reference hour = ( h >= 0 && h < 24 ) ? h : 0; enable cascaded member to time 6. cpp (2 of 5) function calls. return *this; // enables cascading } // end function set. Hour 42 2003 Prentice Hall, Inc. All rights reserved. 38

43 44 45 46 // set minute value Time &Time: : set. Minute( int

43 44 45 46 // set minute value Time &Time: : set. Minute( int m ) { Return *this as reference minute = ( m >= 0 && m < 60 ) ? m : 0; enable cascaded member 47 48 return *this; // enables cascading 49 50 } // end function set. Minute 51 52 53 54 55 // set second value Time &Time: : set. Second( int s ) { Return *this as reference second = ( s >= 0 && s < 60 ) ? s : 0; enable cascaded member Outline to function calls. 56 57 return *this; // enables cascading 58 59 } // end function set. Second 60 61 62 63 64 // get hour value int Time: : get. Hour() const { return hour; 65 66 } // end function get. Hour function calls. to time 6. cpp (3 of 5) 67 2003 Prentice Hall, Inc. All rights reserved. 39

68 69 70 71 // get minute value int Time: : get. Minute() const

68 69 70 71 // get minute value int Time: : get. Minute() const { return minute; 72 73 } // end function get. Minute 74 75 76 77 78 // get second value int Time: : get. Second() const { return second; 79 80 } // end function get. Second 81 82 83 84 85 86 87 // print Time in universal format void Time: : print. Universal() const { cout << setfill( '0' ) << setw( 2 ) << hour << ": " << setw( 2 ) << minute << ": " << setw( 2 ) << second; 88 89 } // end function print. Universal Outline time 6. cpp (4 of 5) 90 2003 Prentice Hall, Inc. All rights reserved. 40

91 92 93 94 95 96 97 // print Time in standard format void

91 92 93 94 95 96 97 // print Time in standard format void Time: : print. Standard() const { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ": " << setfill( '0' ) << setw( 2 ) << minute << ": " << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 98 99 } // end function print. Standard Outline time 6. cpp (5 of 5) 2003 Prentice Hall, Inc. All rights reserved. 41

1 2 3 // Fig. 7. 16: fig 07_16. cpp // Cascading member function

1 2 3 // Fig. 7. 16: fig 07_16. cpp // Cascading member function calls with the this pointer. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include "time 6. h" // Time class definition 9 10 11 12 int main() { Time t; 13 14 15 Cascade member function calls; recall dot operator associates from left to right. // cascaded function calls Outline fig 07_16. cpp (1 of 2) t. set. Hour( 18 ). set. Minute( 30 ). set. Second( 22 ); 16 17 18 19 // output time in universal and standard formats cout << "Universal time: "; t. print. Universal(); 20 21 22 cout << "n. Standard time: "; t. print. Standard(); 23 24 cout << "nn. New standard time: "; 25 2003 Prentice Hall, Inc. All rights reserved. 42

26 27 // cascaded function calls t. set. Time( 20, 20 ). print. Standard();

26 27 // cascaded function calls t. set. Time( 20, 20 ). print. Standard(); 28 29 cout << endl; 30 31 return 0; 32 33 } // end main Universal time: 18: 30: 22 Standard time: 6: 30: 22 PM New standard time: 8: 20 PM Outline Function call to print. Standard must appear last; print. Standard does not return reference to t. fig 07_16. cpp (2 of 2) fig 07_16. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 43

7. 6 Dynamic Memory Management with Operators new and delete • Dynamic memory management

7. 6 Dynamic Memory Management with Operators new and delete • Dynamic memory management – Control allocation and deallocation of memory – Operators new and delete • Include standard header <new> – Access to standard version of new 2003 Prentice Hall, Inc. All rights reserved. 44

7. 6 Dynamic Memory Management with Operators new and delete • new – Consider

7. 6 Dynamic Memory Management with Operators new and delete • new – Consider Time *time. Ptr; time. Ptr = new Time; – new operator • Creates object of proper size for type Time – Error if no space in memory for object • Calls default constructor for object • Returns pointer of specified type – Providing initializers double *ptr = new double( 3. 14159 ); Time *time. Ptr = new Time( 12, 0, 0 ); – Allocating arrays int *grades. Array = new int[ 10 ]; 2003 Prentice Hall, Inc. All rights reserved. 45

7. 6 Dynamic Memory Management with Operators new and delete • delete – Destroy

7. 6 Dynamic Memory Management with Operators new and delete • delete – Destroy dynamically allocated object and free space – Consider delete time. Ptr; – Operator delete • Calls destructor for object • Deallocates memory associated with object – Memory can be reused to allocate other objects – Deallocating arrays delete [] grades. Array; – Deallocates array to which grades. Array points • If pointer to array of objects • First calls destructor for each object in array • Then deallocates memory 2003 Prentice Hall, Inc. All rights reserved. 46

47 7. 7 static Class Members • static class variable – “Class-wide” data •

47 7. 7 static Class Members • static class variable – “Class-wide” data • Property of class, not specific object of class – Efficient when single copy of data is enough • Only the static variable has to be updated – May seem like global variables, but have class scope • Only accessible to objects of same class – Initialized exactly once at file scope – Exist even if no objects of class exist – Can be public, private or protected 2003 Prentice Hall, Inc. All rights reserved.

48 7. 7 static Class Members • Accessing static class variables – Accessible through

48 7. 7 static Class Members • Accessing static class variables – Accessible through any object of class – public static variables • Can also be accessed using binary scope resolution operator(: : ) Employee: : count – private static variables • When no class member objects exist – Can only be accessed via public static member function – To call public static member function combine class name, binary scope resolution operator (: : ) and function name Employee: : get. Count() 2003 Prentice Hall, Inc. All rights reserved.

49 7. 7 static Class Members • static member functions – Cannot access non-static

49 7. 7 static Class Members • static member functions – Cannot access non-static data or functions – No this pointer for static functions • static data members and static member functions exist independent of objects 2003 Prentice Hall, Inc. All rights reserved.

1 2 3 4 // Fig. 7. 17: employee 2. h // Employee class

1 2 3 4 // Fig. 7. 17: employee 2. h // Employee class definition. #ifndef EMPLOYEE 2_H #define EMPLOYEE 2_H 5 6 class Employee { 7 8 9 10 11 12 public: Employee( const char *, const char * ); // constructor ~Employee(); // destructor const char *get. First. Name() const; // return first name static member const char *get. Last. Name() const; // return last name 13 14 15 16 17 18 19 Outline function can only access static data // static member function members and member static int get. Count(); // return # objects instantiated functions. private: char *first. Name; char *last. Name; employee 2. h (1 of 2) static data member is class -wide data. 20 21 22 // static data member static int count; // number of objects instantiated 23 24 }; // end class Employee 50 25 2003 Prentice Hall, Inc. All rights reserved.

51 26 #endif 1 2 3 // Fig. 7. 18: employee 2. cpp //

51 26 #endif 1 2 3 // Fig. 7. 18: employee 2. cpp // Member-function definitions for class Employee. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 #include <new> // C++ standard new operator #include <cstring> // strcpy and strlen prototypes employee 2. h (2 of 2) 10 11 Initialize static #include "employee 2. h" // Employee class definition 12 13 14 employee 2. cpp (1 of 3) int Employee: : count = 0; 15 16 17 18 19 20 21 22 Outline data member exactly once at file // define and initialize static data memberscope. static member function data // define static member function that returns number of accesses static // Employee objects instantiated member count. int Employee: : get. Count() { return count; } // end static function get. Count 2003 Prentice Hall, Inc. All rights reserved.

23 24 25 26 27 28 29 30 // constructor dynamically allocates space for

23 24 25 26 27 28 29 30 // constructor dynamically allocates space for // first and last name and uses strcpy to copy // first and last names into the object Employee: : Employee( const char *first, const char *last ) new operator dynamically { allocates space. first. Name = new char[ strlen( first ) + 1 ]; strcpy( first. Name, first ); 31 32 33 Use static data member last. Name = new char[ strlen( last ) + 1 ]; strcpy( last. Name, last ); store total count of Outline to employees. 34 35 ++count; // increment static count of employees 36 37 38 cout << "Employee constructor for " << first. Name << ' ' << last. Name << " called. " << endl; 39 40 } // end Employee constructor 41 42 43 44 45 46 // destructor deallocates dynamically allocated memory Employee: : ~Employee() { cout << "~Employee() called for " << first. Name << ' ' << last. Name << endl; employee 2. cpp (2 of 3) 47 2003 Prentice Hall, Inc. All rights reserved. 52

48 49 delete [] first. Name; // recapture memory delete [] last. Name; //

48 49 delete [] first. Name; // recapture memory delete [] last. Name; // recapture memory 50 51 --count; // decrement static count of employees 52 53 Use static } // end destructor ~Employee 54 55 56 57 58 59 60 61 // return first name of employees. const char *Employee: : get. First. Name() const { // const before return type prevents client from modifying // private data; client should copy returned string before // destructor deletes storage to prevent undefined pointer return first. Name; 62 63 } // end function get. First. Name 64 65 66 67 68 69 70 71 // return last name of employee const char *Employee: : get. Last. Name() const { // const before return type prevents client from modifying // private data; client should copy returned string before // destructor deletes storage to prevent undefined pointer return last. Name; 72 73 } // end function get. Last. Name Outline Operator deletetodeallocates data member store totalmemory. count of employee 2. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 53

1 2 3 // Fig. 7. 19: fig 07_19. cpp // Driver to test

1 2 3 // Fig. 7. 19: fig 07_19. cpp // Driver to test class Employee. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <new> // C++ standard new operator 9 10 #include "employee 2. h" // Employee class definition 11 12 13 14 15 int main() { cout << "Number of employees before instantiation is " << Employee: : get. Count() << endl; // use class name 16 17 18 Employee *e 1 Ptr = new Employee( "Susan", "Baker" ); static member function Employee *e 2 Ptr = new Employee( "Robert", "Jones" ); 19 20 21 << e 1 Ptr->get. Count(); Outline fig 07_19. cpp (1 of 2) new operator dynamically allocates space. can be invoked on any object of class. cout << "Number of employees after instantiation is " 22 2003 Prentice Hall, Inc. All rights reserved. 54

23 24 25 26 27 28 cout << "nn. Employee 1: " << e

23 24 25 26 27 28 cout << "nn. Employee 1: " << e 1 Ptr->get. First. Name() << " " << e 1 Ptr->get. Last. Name() << "n. Employee 2: " << e 2 Ptr->get. First. Name() << " " << e 2 Ptr->get. Last. Name() << "nn"; 29 30 31 32 33 delete e 1 Ptr; // recapture memory e 1 Ptr = 0; // disconnect pointer from free-store space delete e 2 Ptr; // recapture memory static member function e 2 Ptr = 0; // disconnect pointer from free-store space 34 35 36 invoked using binary scope Operatorresolution delete deallocates cout << "Number of employees after deletion is " operator (no memory. << Employee: : get. Count() << endl; existing class objects). 37 38 return 0; 39 40 } // end main Outline fig 07_19. cpp (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 55

Number of employees before instantiation is 0 Employee constructor for Susan Baker called. Employee

Number of employees before instantiation is 0 Employee constructor for Susan Baker called. Employee constructor for Robert Jones called. Number of employees after instantiation is 2 Outline Employee 1: Susan Baker Employee 2: Robert Jones ~Employee() called for Susan Baker ~Employee() called for Robert Jones Number of employees after deletion is 0 fig 07_19. cpp output (1 of 1) 2003 Prentice Hall, Inc. All rights reserved. 56

7. 8 Data Abstraction and Information Hiding • Information hiding – Classes hide implementation

7. 8 Data Abstraction and Information Hiding • Information hiding – Classes hide implementation details from clients – Example: stack data structure • • Data elements added (pushed) onto top Data elements removed (popped) from top Last-in, first-out (LIFO) data structure Client only wants LIFO data structure – Does not care how stack implemented • Data abstraction – Describe functionality of class independent of implementation 2003 Prentice Hall, Inc. All rights reserved. 57

7. 8 Data Abstraction and Information Hiding • Abstract data types (ADTs) – Approximations/models

7. 8 Data Abstraction and Information Hiding • Abstract data types (ADTs) – Approximations/models of real-world concepts and behaviors • int, float are models for a numbers – Data representation – Operations allowed on those data • C++ extensible – Standard data types cannot be changed, but new data types can be created 2003 Prentice Hall, Inc. All rights reserved. 58

59 7. 8. 1 Example: Array Abstract Data Type • ADT array – Could

59 7. 8. 1 Example: Array Abstract Data Type • ADT array – Could include • Subscript range checking • Arbitrary range of subscripts – Instead of having to start with 0 • Array assignment • Array comparison • Array input/output • Arrays that know their sizes • Arrays that expand dynamically to accommodate more elements 2003 Prentice Hall, Inc. All rights reserved.

60 7. 8. 2 Example: String Abstract Data Type • Strings in C++ –

60 7. 8. 2 Example: String Abstract Data Type • Strings in C++ – C++ does not provide built-in string data type • Maximizes performance – Provides mechanisms for creating and implementing string abstract data type • String ADT (Chapter 8) – ANSI/ISO standard string class (Chapter 19) 2003 Prentice Hall, Inc. All rights reserved.

61 7. 8. 3 Example: Queue Abstract Data Type • Queue – FIFO •

61 7. 8. 3 Example: Queue Abstract Data Type • Queue – FIFO • First in, first out – Enqueue • Put items in queue one at a time – Dequeue • Remove items from queue one at a time • Queue ADT – Implementation hidden from clients • Clients may not manipulate data structure directly – Only queue member functions can access internal data – Queue ADT (Chapter 15) – Standard library queue class (Chapter 20) 2003 Prentice Hall, Inc. All rights reserved.

62 7. 9 Container Classes and Iterators • Container classes (collection classes) – Designed

62 7. 9 Container Classes and Iterators • Container classes (collection classes) – Designed to hold collections of objects – Common services • Insertion, deletion, searching, sorting, or testing an item – Examples • Arrays, stacks, queues, trees and linked lists • Iterator objects (iterators) – Returns next item of collection • Or performs some action on next item – Can have several iterators per container • Book with multiple bookmarks – Each iterator maintains own “position” – Discussed further in Chapter 20 2003 Prentice Hall, Inc. All rights reserved.

63 7. 10 Proxy Classes • Proxy class – Hide implementation details of another

63 7. 10 Proxy Classes • Proxy class – Hide implementation details of another class – Knows only public interface of class being hidden – Enables clients to use class’s services without giving access to class’s implementation • Forward class declaration – – Used when class definition only uses pointer to another class Prevents need for including header file Declares class before referencing Format: class Class. To. Load; 2003 Prentice Hall, Inc. All rights reserved.

1 2 // Fig. 7. 20: implementation. h // Header file for class Implementation

1 2 // Fig. 7. 20: implementation. h // Header file for class Implementation 3 4 class Implementation { 5 6 public: 7 8 9 10 11 12 // constructor Implementation( int v ) : value( v ) // initialize value with v { // empty body 13 14 } // end Implementation constructor 15 16 17 18 19 // set value to v void set. Value( int v ) { value = v; // should validate v 20 21 } // end function set. Value Outline public member function. implementation. h (1 of 2) 22 2003 Prentice Hall, Inc. All rights reserved. 64

23 24 25 26 // return value int get. Value() const { return value;

23 24 25 26 // return value int get. Value() const { return value; 27 28 } // end function get. Value 29 30 31 private: int value; 32 33 }; // end class Implementation Outline public member function. implementation. h (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 65

1 2 // Fig. 7. 21: interface. h // Header file for interface. cpp

1 2 // Fig. 7. 21: interface. h // Header file for interface. cpp 3 4 class Implementation; // forward class declaration 5 6 class Interface { 7 8 9 10 11 12 Provide same public interface as class public: Implementation; recall Interface( int ); set. Value and get. Value void set. Value( int ); // same public interface as only public member int get. Value() const; // class Implementation ~Interface(); functions. 13 14 private: 15 16 17 18 19 Pointer to Implementation object // requires previous forward declaration (line 4) requires forward class Implementation *ptr; declaration. Outline interface. h (1 of 1) }; // end class Interface 2003 Prentice Hall, Inc. All rights reserved. 66

1 2 3 4 // Fig. 7. 22: interface. cpp // Definition of class

1 2 3 4 // Fig. 7. 22: interface. cpp // Definition of class Interface #include "interface. h" // Interface class definition #include "implementation. h" // Implementation class definition 5 6 7 8 9 10 // empty body 11 12 } // end Interface constructor Outline Maintain pointer to underlying // constructor Proxy class Interface Implementation object. Interface: : Interface( int v ) : ptr ( new Implementation( v ) ) // initialize ptr includes header file for class { Implementation. 13 14 15 16 17 // call Implementation's set. Value function Invoke corresponding void Interface: : set. Value( int v ) function on underlying { Implementation object. ptr->set. Value( v ); 18 19 } // end function set. Value interface. cpp (1 of 2) 20 2003 Prentice Hall, Inc. All rights reserved. 67

21 22 23 24 // call Implementation's get. Value function int Interface: : get.

21 22 23 24 // call Implementation's get. Value function int Interface: : get. Value() const { return ptr->get. Value(); 25 26 } // end function get. Value 27 28 29 30 31 // destructor Interface: : ~Interface() { delete ptr; 32 33 } // end destructor ~Interface Invoke corresponding function on underlying Implementation object. Outline Deallocate underlying Implementation object. interface. cpp (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 68

1 2 3 // Fig. 7. 23: fig 07_23. cpp // Hiding a class’s

1 2 3 // Fig. 7. 23: fig 07_23. cpp // Hiding a class’s private data with a proxy class. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include "interface. h" // Interface class definition Outline Only include proxy class header file. Create object of proxy class Interface; note no mention of Implementation class. 9 10 11 12 13 14 15 int main() { Interface i( 5 ); cout << "Interface contains: " << i. get. Value() << " before set. Value" << endl; 16 17 i. set. Value( 10 ); 18 19 20 cout << "Interface contains: " << i. get. Value() << " after set. Value" << endl; 21 22 return 0; 23 24 } // end main fig 07_23. cpp (1 of 1) fig 07_23. cpp Invoke member functions via output (1 of 1) proxy class object. Interface contains: 5 before set. Value Interface contains: 10 after set. Value 2003 Prentice Hall, Inc. All rights reserved. 69