1 6 1 Introduction Objectoriented programming OOP Encapsulates
1 6. 1 Introduction • Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior) into packages called classes • Information hiding – Class objects communicate across well-defined interfaces – Implementation details hidden within classes themselves • User-defined (programmer-defined) types: classes – – Data (data members) Functions (member functions or methods) Similar to blueprints – reusable Class instance: object 2003 Prentice Hall, Inc. All rights reserved.
6. 5 Implementing a Time Abstract Data Type with a class • Classes – Model objects • Attributes (data members) • Behaviors (member functions) – Defined using keyword class – Member functions • Methods • Invoked in response to messages • Member access specifiers – public: • Accessible wherever object of class in scope – private: • Accessible only to member functions of class – protected: 2003 Prentice Hall, Inc. All rights reserved. 2
6. 5 Implementing a Time Abstract Data Type with a class • Constructor function – Special member function • Initializes data members • Same name as class – Called when object instantiated – Several constructors • Function overloading – No return type 2003 Prentice Hall, Inc. All rights reserved. 3
1 class Time { 2 3 4 5 6 7 public: Function prototypes for Definition of class begins with Time(); constructor Class//body startspublic with left member functions. keyword class. void set. Time( int, int brace. ); // set hour, minute, second access specifiers. void print. Universal(); Member // print universal-time format Constructor has same name as void print. Standard(); // print standard-time format 8 9 10 11 12 private: int hour; int minute; int second; 13 14 }; // end class Time Outline 4 Class Time definition (1 of 1) class, private Time, anddata no return members type. accessible only to member // 0 - 23 (24 -hour clock format) functions. Class body ends with // Definition 0 - 59 terminatesright with brace. // 0 - 59 semicolon. 2003 Prentice Hall, Inc. All rights reserved.
6. 5 Implementing a Time Abstract Data Type with a class • Objects of class – After class definition • Class name new type specifier – C++ extensible language • Object, array, pointer and reference declarations – Example: Time Class name becomes new type specifier. sunset; array. Of. Times[ 5 ]; *pointer. To. Time; &dinner. Time = sunset; 2003 Prentice Hall, Inc. All rights reserved. // // object of type Time array of Time objects pointer to a Time object reference to a Time object 5
6. 5 Implementing a Time Abstract Data Type with a class • Member functions defined outside class – Binary scope resolution operator (: : ) • “Ties” member name to class name • Uniquely identify functions of particular class • Different classes can have member functions with same name – Format for defining member functions Return. Type Class. Name: : Member. Function. Name( ){ … } – Does not change whether function public or private • Member functions defined inside class – Do not need scope resolution operator, class name – Compiler attempts inline • Outside class, inline explicitly with keyword inline 2003 Prentice Hall, Inc. All rights reserved. 6
1 2 3 // Fig. 6. 3: fig 06_03. cpp // Time class. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 #include <iomanip> 9 10 11 using std: : setfill; using std: : setw; 12 13 14 15 16 17 18 19 20 21 Outline fig 06_03. cpp (1 of 5) Define class Time. // Time abstract data type (ADT) definition class Time { public: Time(); // constructor void set. Time( int, int ); // set hour, minute, second void print. Universal(); // print universal-time format void print. Standard(); // print standard-time format 2003 Prentice Hall, Inc. All rights reserved. 7
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 private: int hour; int minute; int second; Outline // 0 - 23 (24 -hour clock format) // 0 - 59 fig 06_03. cpp (2 of 5) }; // end class Time // Time constructor initializes each data member to zero and Constructor initializes // ensures all Time objects start in a consistent state private data members Time: : Time() to 0. { hour = minute = second = 0; } // end Time constructor // set new Time value using universal time, perform validity // checks on the data values and set invalid values to zero public member void Time: : set. Time( int h, int m, int s ) function checks { parameter values for hour = ( h >= 0 && h < 24 ) ? h : 0; validity before setting minute = ( m >= 0 && m < 60 ) ? m : 0; private data second = ( s >= 0 && s < 60 ) ? s : 0; members. } // end function set. Time 46 2003 Prentice Hall, Inc. All rights reserved. 8
47 48 49 50 51 52 // print Time in universal format void Time: : print. Universal() { cout << setfill( '0' ) << setw( 2 ) << hour << ": " << setw( 2 ) << minute << ": " << setw( 2 ) << second; 53 54 } // end function print. Universal 55 56 57 58 59 60 61 62 // print Time in standard format void Time: : print. Standard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ": " << setfill( '0' ) << setw( 2 ) << minute << ": " << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 63 64 } // end function print. Standard Declare variable 65 66 67 68 int main() { Time t; Outline fig 06_03. cpp (3 of 5) No arguments (implicitly “know” purpose is to print data members); member function calls more concise. t to be object of class Time. // instantiate object t of class Time 69 2003 Prentice Hall, Inc. All rights reserved. 9
70 71 72 // output Time object t's initial values cout << "The initial universal time is " ; t. print. Universal(); // 00: 00 73 74 75 cout << "n. The initial standard time is " ; functions t. print. Standard(); // 12: 00 AM 76 77 t. set. Time( 13, 27, 6 ); 78 79 80 81 // output Time object t's new values Set data members cout << "nn. Universal time after set. Time "; publicis member t. print. Universal(); // 13: 27: 06 82 83 84 cout << "n. Standard time after set. Time is " ; to invalid values t. print. Standard(); // 1: 27: 06 PM 85 86 t. set. Time( 99, 99 ); 87 88 89 90 91 // output t's values after specifying invalid values cout << "nn. After attempting invalid settings: " << "n. Universal time: "; t. print. Universal(); // 00: 00 Outline Invoke public member to print time. fig 06_03. cpp (4 of 5) // change time using function. Attempt to set data members using public member function. // attempt invalid settings 92 2003 Prentice Hall, Inc. All rights reserved. 10
93 94 95 cout << "n. Standard time: "; t. print. Standard(); // 12: 00 AM cout << endl; 96 97 return 0; 98 99 Outline fig 06_03. cpp (5 of 5) } // end main fig 06_03. cpp output (1 of 1) The initial universal time is 00: 00 The initial standard time is 12: 00 AM Universal time after set. Time is 13: 27: 06 Standard time after set. Time is 1: 27: 06 PM After attempting invalid settings: Universal time: 00: 00 Standard time: 12: 00 AM Data members set to 0 after attempting invalid settings. 2003 Prentice Hall, Inc. All rights reserved. 11
6. 5 Implementing a Time Abstract Data Type with a class • Destructors – Same name as class • Preceded with tilde (~) – No arguments – Cannot be overloaded – Performs “termination housekeeping” 2003 Prentice Hall, Inc. All rights reserved. 12
6. 5 Implementing a Time Abstract Data Type with a class • Advantages of using classes – Simplify programming – Interfaces • Hide implementation – Software reuse • Composition (aggregation) – Class objects included as members of other classes • Inheritance – New classes derived from old 2003 Prentice Hall, Inc. All rights reserved. 13
6. 6 Class Scope and Accessing Class Members • Class scope – Data members, member functions – Within class scope • Class members – Immediately accessible by all member functions – Referenced by name – Outside class scope • Referenced through handles – Object name, reference to object, pointer to object • File scope – Nonmember functions 2003 Prentice Hall, Inc. All rights reserved. 14
6. 6 Class Scope and Accessing Class Members • Function scope – Variables declared in member function – Only known to function – Variables with same name as class-scope variables • Class-scope variable “hidden” – Access with scope resolution operator (: : ) Class. Name: : class. Variable. Name – Variables only known to function they are defined in – Variables are destroyed after function completion 2003 Prentice Hall, Inc. All rights reserved. 15
6. 6 Class Scope and Accessing Class Members • Operators to access class members – Identical to those for structs – Dot member selection operator (. ) • Object • Reference to object – Arrow member selection operator (->) • Pointers 2003 Prentice Hall, Inc. All rights reserved. 16
17 Pointers to structures – Print member hour of time. Object: cout << time. Object. hour; OR time. Ptr = &time. Object; cout << time. Ptr->hour; – time. Ptr->hour same as ( *time. Ptr ). hour • Parentheses required – * lower precedence than. 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 // Fig. 6. 4: fig 06_04. cpp // Demonstrating the class member access operators. and -> // // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! #include <iostream> 6 7 8 using std: : cout; using std: : endl; 9 10 11 // class Count definition class Count { 12 13 14 public: int x; 15 16 17 18 19 20 21 Outline fig 06_04. cpp (1 of 2) Data member x public to illustrate class member access operators; typically data members private. void print() { cout << x << endl; } }; // end class Count 22 2003 Prentice Hall, Inc. All rights reserved. 18
23 24 25 26 27 28 29 30 31 int main() { Count counter; // create counter object Count *counter. Ptr = &counter; // create pointer to counter Count &counter. Ref = counter; // Use create reference to counter dot member selection operator for counter object. cout << "Assign 1 to x and print using the object's name: " ; counter. x = 1; // assign 1 to data member x dot member counter. print(); // call member. Use function printselection fig 06_04. cpp (2 of 2) fig 06_04. cpp output (1 of 1) operator for counter. Ref using a reference: reference to object. " ; 32 33 34 35 cout << "Assign 2 to x and print counter. Ref. x = 2; // assign 2 to data member x arrow print member counter. Ref. print(); // call member Use function 36 37 38 39 cout << "Assign 3 to x and print counter. Ptr->x = 3; // assign 3 to data member x counter. Ptr->print(); // call member function print 40 41 return 0; 42 43 Outline selection operator for counter. Ptr using a pointer: pointer to object. " ; } // end main Assign 1 to x and print using the object's name: 1 Assign 2 to x and print using a reference: 2 Assign 3 to x and print using a pointer: 3 2003 Prentice Hall, Inc. All rights reserved. 19
6. 7 Separating Interface from Implementation • Separating interface from implementation – Advantage • Easier to modify programs – Disadvantage • Header files – Portions of implementation • Inline member functions – Hints about other implementation • private members • Can hide more with proxy class 2003 Prentice Hall, Inc. All rights reserved. 20
6. 7 Separating Interface from Implementation • Header files – Class definitions and function prototypes – Included in each file using class • #include – File extension. h • Source-code files – Member function definitions – Same base name • Convention – Compiled and linked 2003 Prentice Hall, Inc. All rights reserved. 21
1 2 3 // Fig. 6. 5: time 1. h // Declaration of class Time. // Member functions are defined in time 1. cpp Preprocessor 4 5 6 7 // prevent multiple inclusions of header file #ifndef TIME 1_H #define TIME 1_H 8 9 10 // Time abstract data typedefined”Preprocessor definition “If not directive not included if name class Time { Naming convention: 11 12 13 14 15 16 public: Time(); // constructor void set. Time( int, int ); // set hour, minute, second void print. Universal(); // print universal-time format void print. Standard(); // print standard-time format 17 18 19 20 21 private: int hour; int minute; int second; 22 23 }; // end class Time 24 25 #endif code to prevent multiple inclusions. Outline time 1. h (1 of 1) Code between these directives defines name TIME 1_H already defined. header file name with underscore replacing period. // 0 - 23 (24 -hour clock format) // 0 - 59 2003 Prentice Hall, Inc. All rights reserved. 22
1 2 3 // Fig. 6. 6: time 1. 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 1. h #include "time 1. h" 14 15 16 17 18 19 // Time constructor initializes each data member to zero. // Ensures all Time objects Name start of in header a consistent state. file enclosed Time: : Time() in quotes; angle brackets { cause preprocessor to assume hour = minute = second = 0; 20 21 } // end Time constructor Outline time 1. cpp (1 of 3) Include header file time 1. h. header part of C++ Standard Library. 22 2003 Prentice Hall, Inc. All rights reserved. 23
23 24 25 26 27 28 29 // Set new Time value using universal time. Perform validity // checks on the data values. Set invalid values to zero. void Time: : set. Time( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; 30 31 } // end function set. Time 32 33 34 35 36 37 38 // print Time in universal format void Time: : print. Universal() { cout << setfill( '0' ) << setw( 2 ) << hour << ": " << setw( 2 ) << minute << ": " << setw( 2 ) << second; 39 40 } // end function print. Universal Outline time 1. cpp (2 of 3) 41 2003 Prentice Hall, Inc. All rights reserved. 24
42 43 44 45 46 47 48 // print Time in standard format void Time: : print. Standard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ": " << setfill( '0' ) << setw( 2 ) << minute << ": " << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 49 50 } // end function print. Standard Outline time 1. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 25
1 2 3 4 // Fig. 6. 7: fig 06_07. cpp // Program to test class Time. // NOTE: This file must be compiled with time 1. cpp. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 11 12 13 14 // include definition of class Time #include "time 1. h" int main() { Time t; Outline fig 06_07. cpp (1 of 2) Include header file time 1. h to ensure correct from time 1. h creation/manipulation and determine size of Time class object. // instantiate object t of class Time 15 16 17 18 19 20 // output Time object t's initial values cout << "The initial universal time is " ; t. print. Universal(); // 00: 00 cout << "n. The initial standard time is " ; t. print. Standard(); // 12: 00 AM 21 22 t. set. Time( 13, 27, 6 ); // change time 23 2003 Prentice Hall, Inc. All rights reserved. 26
24 25 26 27 28 // output Time object t's new values cout << "nn. Universal time after set. Time is " ; t. print. Universal(); // 13: 27: 06 cout << "n. Standard time after set. Time is " ; t. print. Standard(); // 1: 27: 06 PM 29 30 t. set. Time( 99, 99 ); 31 32 33 34 35 36 37 38 // output t's values after specifying invalid values cout << "nn. After attempting invalid settings: " << "n. Universal time: "; t. print. Universal(); // 00: 00 cout << "n. Standard time: "; t. print. Standard(); // 12: 00 AM cout << endl; 39 40 return 0; 41 42 // attempt invalid settings Outline fig 06_07. cpp (2 of 2) fig 06_07. cpp output (1 of 1) } // end main The initial universal time is 00: 00 The initial standard time is 12: 00 AM Universal time after set. Time is 13: 27: 06 Standard time after set. Time is 1: 27: 06 PM 2003 Prentice Hall, Inc. All rights reserved. 27
28 6. 8 Controlling Access to Members • Access modes – private • Default access mode • Accessible to member functions and friends – public • Accessible to any function in program with handle to class object – protected • Chapter 9 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 // Fig. 6. 8: fig 06_08. cpp // Demonstrate errors resulting from attempts // to access private class members. #include <iostream> 5 6 using std: : cout; 7 8 9 // include definition of class Time from time 1. h #include "time 1. h" 10 11 12 13 int main() { Time t; 14 15 16 17 18 19 20 21 22 23 Outline fig 06_08. cpp (1 of 1) Recall data member hour is private; attempts to access private members results in Data member minute also t. hour = 7; // error: 'Time: : hour' error. is not accessible private; attempts to access // error: 'Time: : minute' is not accessible private members produces cout << "minute = " << t. minute; error. // create Time object return 0; } // end main 2003 Prentice Hall, Inc. All rights reserved. 29
D: cpphtp 4_examplesch 06Fig 6_06Fig 06_06. cpp(16) : error C 2248: 'hour' : cannot access private member declared in class 'Time' D: cpphtp 4_examplesch 06Fig 6_06Fig 06_06. cpp(19) : error C 2248: 'minute' : cannot access private member declared in class 'Time' Outline fig 06_08. cpp output (1 of 1) Errors produced by attempting to access private members. 2003 Prentice Hall, Inc. All rights reserved. 30
31 6. 8 Controlling Access to Members • Class member access – Default private – Explicitly set to private, public, protected • struct member access – Default public – Explicitly set to private, public, protected • Access to class’s private data – Controlled with access functions (accessor methods) • Get function – Read private data • Set function – Modify private data 2003 Prentice Hall, Inc. All rights reserved.
32 6. 9 Access Functions and Utility Functions • Access functions – public – Read/display data – Predicate functions • Check conditions • Utility functions (helper functions) – private – Support operation of public member functions – Not intended for direct client use 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 5 // Fig. 6. 9: salesp. h // Sales. Person class definition. // Member functions defined in salesp. cpp. #ifndef SALESP_H #define SALESP_H 6 7 class Sales. Person { 8 9 10 11 12 13 14 15 16 17 private: double total. Annual. Sales(); double sales[ 12 ]; 18 19 }; // end class Sales. Person 20 21 #endif Outline salesp. h (1 of 1) Set access function performs validity constructor checks. public: Sales. Person(); // void get. Sales. From. User(); // input sales from keyboard void set. Sales( int, double ); // set sales for a month private utility void print. Annual. Sales(); // summarize and print sales function. // utility function // 12 monthly sales figures 2003 Prentice Hall, Inc. All rights reserved. 33
1 2 3 // Fig. 6. 10: salesp. cpp // Member functions for class Sales. Person. #include <iostream> 4 5 6 7 8 using 9 10 #include <iomanip> 11 12 using std: : setprecision; 13 14 15 // include Sales. Person class definition from salesp. h #include "salesp. h" 16 17 18 19 20 21 // initialize elements of array sales to 0. 0 Sales. Person: : Sales. Person() { for ( int i = 0; i < 12; i++ ) sales[ i ] = 0. 0; 22 23 } // end Sales. Person constructor std: : cout; std: : cin; std: : endl; std: : fixed; Outline salesp. cpp (1 of 3) 24 2003 Prentice Hall, Inc. All rights reserved. 34
25 26 27 28 // get 12 sales figures from the user at the keyboard void Sales. Person: : get. Sales. From. User() { double sales. Figure; 29 30 31 32 33 for ( int i = 1; i <= 12; i++ ) { cout << "Enter sales amount for month " << i << ": "; cin >> sales. Figure; set. Sales( i, sales. Figure ); 34 35 } // end for 36 37 } // end function get. Sales. From. User 38 39 40 41 42 43 44 45 // set one of the 12 monthly sales figures; function subtracts // one from month value for proper subscript in sales array Set access function performs void Sales. Person: : set. Sales( int month, double amount ) validity checks. { // test for valid month and amount values if ( month >= 1 && month <= 12 && amount > 0 ) sales[ month - 1 ] = amount; // adjust for subscripts 0 -11 46 47 48 Outline salesp. cpp (2 of 3) else // invalid month or amount value cout << "Invalid month or sales figure" << endl; 2003 Prentice Hall, Inc. All rights reserved. 35
49 50 } // end function set. Sales 51 52 53 54 55 56 57 // print total annual sales (with help of utility function) void Sales. Person: : print. Annual. Sales() { cout << setprecision( 2 ) << fixed << "n. The total annual sales are: $" << total. Annual. Sales() << endl; // call utility function 58 59 } // end function print. Annual. Sales 60 61 62 63 64 65 66 67 68 69 70 71 Outline // private utility function to total annual sales double Sales. Person: : total. Annual. Sales() { double total = 0. 0; // initialize total for ( int i = 0; i < 12; i++ ) total += sales[ i ]; salesp. cpp (3 of 3) private utility function to help function print. Annual. Sales; encapsulates logic of manipulating sales array. // summarize sales results return total; } // end function total. Annual. Sales 2003 Prentice Hall, Inc. All rights reserved. 36
1 2 3 // Fig. 6. 11: fig 06_11. cpp // Demonstrating a utility function. // Compile this program with salesp. cpp 4 5 6 // include Sales. Person class definition from salesp. h #include "salesp. h" 7 8 9 10 11 12 13 14 15 16 17 int main() { Sales. Person s; s. get. Sales. From. User(); s. print. Annual. Sales(); // Outline fig 06_11. cpp (1 of 1) Simple sequence of member function calls; logic create Sales. Person object s encapsulated in member functions. note simple sequential code; no // // control structures in main return 0; } // end main 2003 Prentice Hall, Inc. All rights reserved. 37
Enter Enter Enter sales sales sales amount amount amount for for for month month month 1: 5314. 76 2: 4292. 38 3: 4589. 83 4: 5534. 03 5: 4376. 34 6: 5698. 45 7: 4439. 22 8: 5893. 57 9: 4909. 67 10: 5123. 45 11: 4024. 97 12: 5923. 92 Outline fig 06_11. cpp output (1 of 1) The total annual sales are: $60120. 59 2003 Prentice Hall, Inc. All rights reserved. 38
39 6. 10 Initializing Class Objects: Constructors • Constructors – Initialize data members • Or can set later – Same name as class – No return type • Initializers – Passed as arguments to constructor – In parentheses to right of class name before semicolon Class-type Object. Name( value 1, value 2, …); 2003 Prentice Hall, Inc. All rights reserved.
6. 11 Using Default Arguments with Constructors • Constructors – Can specify default arguments – Default constructors • Defaults all arguments OR • Explicitly requires no arguments • Can be invoked with no arguments • Only one per class 2003 Prentice Hall, Inc. All rights reserved. 40
1 2 3 // Fig. 6. 12: time 2. h // Declaration of class Time. // Member functions defined in time 2. cpp. 4 5 6 7 // prevent multiple inclusions of header file #ifndef TIME 2_H #define TIME 2_H 8 9 10 // Time abstract data type definition class Time { 11 12 13 14 15 16 public: Time( int = 0, int = 0); // default constructor void set. Time( int, int ); // set hour, minute, second void print. Universal(); // print universal-time format void print. Standard(); // print standard-time format 17 18 19 20 21 private: int hour; int minute; int second; 22 23 }; // end class Time 24 25 #endif Outline time 2. h (1 of 1) Default constructor specifying all arguments. // 0 - 23 (24 -hour clock format ) // 0 - 59 2003 Prentice Hall, Inc. All rights reserved. 41
1 2 3 // Fig. 6. 13: time 2. 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 2. h #include "time 2. h" 14 15 16 17 18 19 20 21 // Time constructor initializes each data member to zero; // ensures all Time objects start in a consistent state Time: : Time( int hr, int min, int sec ) { set. Time( hr, min, sec ); // validate and set time Outline time 2. cpp (1 of 3) Constructor calls set. Time to validate passed (or default) values. } // end Time constructor 22 2003 Prentice Hall, Inc. All rights reserved. 42
23 24 25 26 27 28 29 // set new Time value using universal time, perform validity // checks on the data values and set invalid values to zero void Time: : set. Time( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; 30 31 } // end function set. Time 32 33 34 35 36 37 38 // print Time in universal format void Time: : print. Universal() { cout << setfill( '0' ) << setw( 2 ) << hour << ": " << setw( 2 ) << minute << ": " << setw( 2 ) << second; 39 40 } // end function print. Universal Outline time 2. cpp (2 of 3) 41 2003 Prentice Hall, Inc. All rights reserved. 43
42 43 44 45 46 47 48 // print Time in standard format void Time: : print. Standard() { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ": " << setfill( '0' ) << setw( 2 ) << minute << ": " << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 49 50 } // end function print. Standard Outline time 2. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 44
1 2 3 // Fig. 6. 14: fig 06_14. cpp // Demonstrating a default constructor for class Time. #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 // include definition of class Time from time 2. h #include "time 2. h" 10 11 12 13 14 15 16 17 int main() { Time t 1; Time t 2( Time t 3( Time t 4( Time t 5( 18 19 20 21 22 23 // 2 ); // 21, 34 ); // 12, 25, 42 ); // 27, 74, 99 ); // Outline fig 06_14. cpp (1 of 2) all arguments defaulted minute and second defaulted all values specified all bad values specified cout << "Constructed with: nn" << "all default arguments: n " ; t 1. print. Universal(); // 00: 00 cout << "n "; t 1. print. Standard(); // 12: 00 AM Initialize Time objects using default arguments. Initialize Time object with invalid values; validity checking will set values to 0. 24 2003 Prentice Hall, Inc. All rights reserved. 45
25 26 27 28 cout << "nnhour specified; default minute and second: n t 2. print. Universal(); // 02: 00 cout << "n "; t 2. print. Standard(); // 2: 00 AM "; 29 30 31 32 33 cout << "nnhour and minute specified; default second: n t 3. print. Universal(); // 21: 34: 00 cout << "n "; t 3. print. Standard(); // 9: 34: 00 PM "; 34 35 36 37 38 cout << "nnhour, minute, and second specified: n t 4. print. Universal(); // 12: 25: 42 cout << "n "; t 4. print. Standard(); // 12: 25: 42 PM 39 40 41 42 43 44 cout << "nnall invalid values specified: n t 5. print. Universal(); // 00: 00 cout << "n "; t 5. print. Standard(); // 12: 00 AM cout << endl; 45 46 return 0; 47 48 "; Outline fig 06_14. cpp (2 of 2) "; t 5 constructed with invalid arguments; values set to 0. } // end main 2003 Prentice Hall, Inc. All rights reserved. 46
Constructed with: all default arguments: 00: 00 12: 00 AM hour specified; default minute and second: 02: 00: 00 AM Outline fig 06_14. cpp output (1 of 1) hour and minute specified; default second: 21: 34: 00 9: 34: 00 PM hour, minute, and second specified: 12: 25: 42 PM all invalid values specified: 00: 00 12: 00 AM 2003 Prentice Hall, Inc. All rights reserved. 47
48 6. 12 Destructors • Destructors – Special member function – Same name as class • Preceded with tilde (~) – – No arguments No return value Cannot be overloaded Performs “termination housekeeping” • Before system reclaims object’s memory – Reuse memory for new objects – If no explicit destructor • Compiler creates “empty” destructor 2003 Prentice Hall, Inc. All rights reserved.
6. 13 When Constructors and Destructors Are Called • Constructors and destructors – Called implicitly by compiler • Order of function calls – Depends on order of execution • When execution enters and exits scope of objects – Generally, destructor calls reverse order of constructor calls 2003 Prentice Hall, Inc. All rights reserved. 49
6. 13 When Constructors and Destructors Are Called • Order of constructor, destructor function calls – Global scope objects • Constructors – Before any other function (including main) • Destructors – When main terminates (or exit function called) – Not called if program terminates with abort – Automatic local objects • Constructors – When objects defined • Each time execution enters scope • Destructors – When objects leave scope • Execution exits block in which object defined – Not called if program ends with exit or abort 2003 Prentice Hall, Inc. All rights reserved. 50
6. 13 When Constructors and Destructors Are Called • Order of constructor, destructor function calls – static local objects • Constructors – Exactly once – When execution reaches point where object defined • Destructors – When main terminates or exit function called – Not called if program ends with abort 2003 Prentice Hall, Inc. All rights reserved. 51
1 2 3 4 5 // Fig. 6. 15: create. h // Definition of class Create. And. Destroy. // Member functions defined in create. cpp. #ifndef CREATE_H #define CREATE_H 6 7 class Create. And. Destroy { 8 9 10 11 public: Create. And. Destroy( int, char * ); // constructor ~Create. And. Destroy(); // destructor private members 12 13 14 15 private: int object. ID; char *message; 16 17 }; // end class Create. And. Destroy 18 19 #endif Outline create. h (1 of 1) Constructor and destructor member functions. to show order of constructor, destructor function calls. 2003 Prentice Hall, Inc. All rights reserved. 52
1 2 3 // Fig. 6. 16: create. cpp // Member-function definitions for class Create. And. Destroy #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 // include Create. And. Destroy class definition from create. h #include "create. h" 10 11 12 13 14 15 16 17 18 19 20 21 // constructor Create. And. Destroy: : Create. And. Destroy( int object. Number, char *message. Ptr ) { object. ID = object. Number; message = message. Ptr; cout << "Object " << object. ID << " << message << endl; Outline create. cpp (1 of 2) Output message to demonstrate timing of constructor function calls. constructor runs " } // end Create. And. Destroy constructor 22 2003 Prentice Hall, Inc. All rights reserved. 53
23 24 25 26 27 28 29 30 31 32 // destructor Create. And. Destroy: : ~Create. And. Destroy() { Output message to // the following line is for pedagogic purposes only timing cout << ( object. ID == 1 || object. IDdemonstrate == 6 ? "n" : "" of ); Outline create. cpp (2 of 2) destructor function calls. cout << "Object " << object. ID << " << message << endl; destructor runs " } // end ~Create. And. Destroy destructor 2003 Prentice Hall, Inc. All rights reserved. 54
1 2 3 4 // Fig. 6. 17: fig 06_17. cpp // Demonstrating the order in which constructors and // destructors are called. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 // include Create. And. Destroy class definition from create. h #include "create. h" 11 12 void create( void ); 13 14 15 // global object Create. And. Destroy first( 1, "(global before main)" ); 16 17 18 19 int main() Create local automatic { cout << "n. MAIN FUNCTION: EXECUTION BEGINS" << endl; 20 21 22 23 24 25 // prototype Outline fig 06_17. cpp (1 of 3) Create variable with global scope. object. Create static local object. Create. And. Destroy second( 2, "(local automatic in main)" ); static Create. And. Destroy third( 3, "(local static in main)" ); 2003 Prentice Hall, Inc. All rights reserved. 55
26 create(); 27 28 cout << "n. MAIN FUNCTION: EXECUTION RESUMES" << endl; 29 30 31 32 33 34 // call function to create objects Outline Create local automatic objects. Create. And. Destroy fourth( 4, "(local automatic in main)" ); fig 06_17. cpp (2 of 3) cout << "n. MAIN FUNCTION: EXECUTION ENDS" << endl; return 0; Create local automatic object. 35 36 } // end main 37 38 39 40 41 // function to create objects void create( void ) Create local automatic object { in function. cout << "n. CREATE FUNCTION: EXECUTION BEGINS" << endl; Create static local object function. automatic in create)" 5, in"(local 42 43 Create. And. Destroy fifth( 44 45 46 Create local static Create. And. Destroy sixth( in function. 6, "(local static in create)" ); 47 48 49 Create. And. Destroy seventh( 7, "(local automatic in create)" ); automatic object 50 2003 Prentice Hall, Inc. All rights reserved. 56
51 52 53 cout << "n. CREATE FUNCTION: EXECUTION ENDS" << endl; Outline } // end function create fig 06_17. cpp (3 of 3) 2003 Prentice Hall, Inc. All rights reserved. 57
Object 1 constructor runs (global before main) MAIN FUNCTION: EXECUTION BEGINS Object 2 constructor runs (local automatic in main) Object 3 constructor runs (local static in main) CREATE Object FUNCTION: EXECUTION BEGINS 5 constructor runs (local automatic in create) 6 constructor runs (local static in create) 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 Object 2 destructor runs Object 6 destructor runs Object 3 destructor runs (local Object 1 (global before main) destructor runs automatic static in Outline fig 06_17. cpp output (1 of 1) Local static object exists Destructors for local Global object constructed until program termination. automatic objects in main beforeautomatic main execution and Local objects called in reverseobject order of Local static last. function destroyed after constructors. constructed on first function execution ends in reverse call and destroyed after main order of construction. execution ends. in main) create) main) 2003 Prentice Hall, Inc. All rights reserved. 58
59 6. 14 Using Set and Get Functions • Set functions – Perform validity checks before modifying private data – Notify if invalid values – Indicate with return values • Get functions – “Query” functions – Control format of data returned 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 // Fig. 6. 18: time 3. h // Declaration of class Time. // Member functions defined in time 3. cpp 4 5 6 7 // prevent multiple inclusions of header file #ifndef TIME 3_H #define TIME 3_H 8 9 class Time { 10 11 12 public: Time( int = 0, int = 0 ); Outline time 3. h (1 of 2) // default constructor 13 14 15 16 17 18 // set functions void set. Time( int, int ); // set hour, minute, second void set. Hour( int ); // set hour void set. Minute( int ); // set minute void set. Second( int ); // set second 19 20 21 22 23 // get functions int get. Hour(); int get. Minute(); int get. Second(); Set functions. Get functions. // return hour // return minute // return second 24 2003 Prentice Hall, Inc. All rights reserved. 60
25 26 void print. Universal(); // output universal-time format void print. Standard(); // output standard-time format 27 28 29 30 31 private: int hour; int minute; int second; 32 33 }; // end clas Time 34 35 #endif // 0 - 23 (24 -hour clock format) // 0 - 59 Outline time 3. h (2 of 2) 2003 Prentice Hall, Inc. All rights reserved. 61
1 2 3 // Fig. 6. 19: time 3. 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 13 // include definition of class Time from time 3. h #include "time 3. 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 hr, int min, int sec ) { set. Time( hr, min, sec ); 21 22 } // end Time constructor Outline time 3. cpp (1 of 4) 23 2003 Prentice Hall, Inc. All rights reserved. 62
24 25 26 27 28 29 // set hour, minute and second values void Time: : set. Time( int h, int m, int s ) { set. Hour( h ); set. Minute( m ); set. Second( s ); 30 31 } // end function set. Time 32 33 34 35 36 37 38 39 40 41 42 43 44 45 Outline time 3. cpp (2 of 4) Call set functions to perform validity checking. // set hour value void Time: : set. Hour( int h ) { hour = ( h >= 0 && h < 24 ) ? h : 0; } // end function set. Hour // set minute value void Time: : set. Minute( int m ) { minute = ( m >= 0 && m < 60 ) ? m : 0; Set functions perform validity checks before modifying data. } // end function set. Minute 46 2003 Prentice Hall, Inc. All rights reserved. 63
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 Set function performs validity // set second value checks before modifying data. void Time: : set. Second( int s ) { second = ( s >= 0 && s < 60 ) ? s : 0; Outline time 3. cpp (3 of 4) } // end function set. Second // return hour value int Time: : get. Hour() { return hour; } // end function get. Hour // return minute value int Time: : get. Minute() { return minute; Get functions allow client to read data. } // end function get. Minute 67 2003 Prentice Hall, Inc. All rights reserved. 64
68 69 70 71 72 73 // return second value int Time: : get. Second() { return second; } // end function get. Second Outline time 3. cpp (4 of 4) Get function allows client to read data. 74 75 76 77 78 79 80 // print Time in universal format void Time: : print. Universal() { 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() { 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. 65
1 2 3 // Fig. 6. 20: fig 06_20. cpp // Demonstrating the Time class set and get functions #include <iostream> 4 5 6 using std: : cout; using std: : endl; 7 8 9 // include definition of class Time from time 3. h #include "time 3. h" 10 11 void increment. Minutes( Time &, const int ); 12 13 14 15 int main() { Time t; 16 17 18 19 20 Outline fig 06_20. cpp (1 of 3) // create Time object // prototype Invoke set functions to set valid values. // set time using individual set functions t. set. Hour( 17 ); // set hour to valid value t. set. Minute( 34 ); // set minute to valid value t. set. Second( 25 ); // set second to valid value 21 2003 Prentice Hall, Inc. All rights reserved. 66
22 23 24 25 26 // use get functions to obtain hour, minute and second cout << "Result of setting all valid values: n" << " Hour: " << t. get. Hour() Attempt to set invalid values << " Minute: " << t. get. Minute() using set functions. fig 06_20. cpp << " Second: " << t. get. Second(); 27 28 29 30 31 // set time using individual set functions t. set. Hour( 234 ); // invalid hour set to 0 t. set. Minute( 43 ); // set minute to valid value t. set. Second( 6373 ); // invalid second set to 0 32 33 34 35 36 37 38 // display hour, minute and second after setting // invalid hour and second values cout << "nn. Result of attempting to set invalid hour and" << " second: n Hour: " << t. get. Hour() Modify data members << " Minute: " << t. get. Minute() function set. Time. << " Second: " << t. get. Second() << "nn"; 39 40 41 t. set. Time( 11, 58, 0 ); increment. Minutes( t, 3 ); 42 43 return 0; 44 45 Outline (2 of 3) Invalid values result in setting data members to 0. using // set time // increment t's minute by 3 } // end main 46 2003 Prentice Hall, Inc. All rights reserved. 67
47 48 49 50 51 52 53 54 55 // add specified number of minutes to a Time object void increment. Minutes( Time &tt, const int count ) { cout << "Incrementing minute " << count << " times: n. Start time: " ; tt. print. Standard(); for ( int i = 0; i < count; i++ ) { tt. set. Minute( ( tt. get. Minute() + 1 ) % 60 ); 56 57 58 if ( tt. get. Minute() == 0 ) tt. set. Hour( ( tt. get. Hour() + 1 ) % 24); 59 60 61 cout << "nminute + 1: "; tt. print. Standard(); 62 63 } // end for 64 65 cout << endl; 66 67 Outline fig 06_20. cpp Using get functions to read (3 of 3) data and set functions to modify data. } // end function increment. Minutes 2003 Prentice Hall, Inc. All rights reserved. 68
Result of setting all valid values: Hour: 17 Minute: 34 Second: 25 Outline Result of attempting to set invalid hour and second: Hour: 0 Minute: 43 Second: 0 Incrementing minute 3 times: Start time: 11: 58: 00 AM minute + 1: 11: 59: 00 AM minute + 1: 12: 00 PM minute + 1: 12: 01: 00 PM fig 06_20. cpp output (1 of 1) Attempting to set data members with invalid values results in error message and members set to 0. 2003 Prentice Hall, Inc. All rights reserved. 69
6. 15 Subtle Trap: Returning a Reference to a private Data Member • Reference to object – Alias for name of object – Lvalue • Can receive value in assignment statement – Changes original object • Returning references – public member functions can return non-const references to private data members • Client able to modify private data members 2003 Prentice Hall, Inc. All rights reserved. 70
1 2 3 // Fig. 6. 21: time 4. h // Declaration of class Time. // Member functions defined in time 4. cpp 4 5 6 7 // prevent multiple inclusions of header file #ifndef TIME 4_H #define TIME 4_H 8 9 class Time { 10 11 12 13 14 public: Time( int = 0, int = 0 ); void set. Time( int, int ); int get. Hour(); 15 16 int &bad. Set. Hour( int ); 17 18 19 20 21 private: int hour; int minute; int second; 22 23 }; // end class Time 24 25 #endif Outline time 4. h (1 of 1) Function to demonstrate effects of returning reference to private data member. // DANGEROUS reference return 2003 Prentice Hall, Inc. All rights reserved. 71
1 2 // Fig. 6. 22: time 4. cpp // Member-function definitions for Time class. 3 4 5 // include definition of class Time from time 4. h #include "time 4. h" 6 7 8 9 10 11 12 // 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 ); 13 14 } // end Time constructor 15 16 17 18 19 20 21 // set values of hour, minute and second void Time: : set. Time( int h, int m, int s ) { hour = ( h >= 0 && h < 24 ) ? h : 0; minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; 22 23 } // end function set. Time Outline time 4. cpp (1 of 2) 24 2003 Prentice Hall, Inc. All rights reserved. 72
25 26 27 28 // return hour value int Time: : get. Hour() { return hour; 29 30 } // end function get. Hour 31 32 33 34 35 36 37 38 39 40 Outline time 4. cpp (2 of 2) // POOR PROGRAMMING PRACTICE: // Returning a reference to a private data member. int &Time: : bad. Set. Hour( int hh ) Return reference to private { data member hour = ( hh >= 0 && hh < 24 ) ? hh : 0; return hour; // DANGEROUS reference return } // end function bad. Set. Hour 2003 Prentice Hall, Inc. All rights reserved. 73
1 2 3 4 // Fig. 6. 23: fig 06_23. cpp // Demonstrating a public member function that // returns a reference to a private data member. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 // include definition of class Time from time 4. h #include "time 4. h" 11 12 13 14 int main() { Time t; Outline fig 06_23. cpp (1 of 2) bad. Set. Hour returns reference to private data member hour. bad. Set. Hour 15 16 17 // store in hour. Ref the reference returned by int &hour. Ref = t. bad. Set. Hour( 20 ); 18 19 cout << "Hour before modification: " << hour. Ref; Reference allows setting 20 21 22 23 24 // use hour. Ref to set invalid hour. Ref = 30; of private data member value in Time object t hour. cout << "n. Hour after modification: " << t. get. Hour(); 25 2003 Prentice Hall, Inc. All rights reserved. 74
26 27 28 // Dangerous: Function call that returns // a reference can be used as an lvalue! t. bad. Set. Hour( 12 ) = 74; 29 30 31 32 33 34 cout << << << 35 36 return 0; 37 38 Outline "nn*****************n" Can use function call as "POOR PROGRAMMING PRACTICE!!!!n" to set invalid value. "bad. Set. Hour as an lvalue, Hour: " t. get. Hour() "n*****************" << endl; lvalue fig 06_23. cpp (2 of 2) fig 06_23. cpp output (1 of 1) } // end main Hour before modification: 20 Hour after modification: 30 ***************** POOR PROGRAMMING PRACTICE!!!! bad. Set. Hour as an lvalue, Hour: 74 ***************** Returning reference allowed invalid setting of private data member hour. 2003 Prentice Hall, Inc. All rights reserved. 75
76 6. 16 Default Memberwise Assignment • Assigning objects – Assignment operator (=) • Can assign one object to another of same type • Default: memberwise assignment – Each right member assigned individually to left member • Passing, returning objects – Objects passed as function arguments – Objects returned from functions – Default: pass-by-value • Copy of object passed, returned – Copy constructor • Copy original values into new object 2003 Prentice Hall, Inc. All rights reserved.
1 2 3 4 // Fig. 6. 24: fig 06_24. cpp // Demonstrating that class objects can be assigned // to each other using default memberwise assignment. #include <iostream> 5 6 7 using std: : cout; using std: : endl; 8 9 10 // class Date definition class Date { 11 12 13 14 public: Date( int = 1, int = 1990 ); // default constructor void print(); 15 16 17 18 19 private: int month; int day; int year; 20 21 }; // end class Date Outline fig 06_24. cpp (1 of 3) 22 2003 Prentice Hall, Inc. All rights reserved. 77
23 24 25 26 27 28 // Date constructor with no range checking Date: : Date( int m, int d, int y ) { month = m; day = d; year = y; 29 30 } // end Date constructor 31 32 33 34 35 // print Date in the format mm-dd-yyyy void Date: : print() { cout << month << '-' << day << '-' << year; 36 37 } // end function print 38 39 40 41 42 int main() { Date date 1( 7, 4, 2002 ); Date date 2; // date 2 defaults to 1/1/1990 Outline fig 06_24. cpp (2 of 3) 43 2003 Prentice Hall, Inc. All rights reserved. 78
44 45 46 47 cout << "date 1 = "; date 1. print(); cout << "ndate 2 = "; date 2. print(); 48 49 date 2 = date 1; 50 51 52 53 cout << "nn. After default memberwise assignment, date 2 = " ; date 2. print(); cout << endl; 54 55 return 0; 56 57 // default Outline Default memberwise assignment assigns each member of date 1 memberwise assignment individually to each member of date 2. fig 06_24. cpp (3 of 3) fig 06_24. cpp output (1 of 1) } // end main date 1 = 7 -4 -2002 date 2 = 1 -1 -1990 After default memberwise assignment, date 2 = 7 -4 -2002 2003 Prentice Hall, Inc. All rights reserved. 79
80 6. 17 Software Reusability • Software reusability – Class libraries • • • Well-defined Carefully tested Well-documented Portable Widely available – Speeds development of powerful, high-quality software • Rapid applications development (RAD) – Resulting problems • Cataloging schemes • Licensing schemes • Protection mechanisms 2003 Prentice Hall, Inc. All rights reserved.
- Slides: 80