CPE 150 Introduction to Programming Chapter 6 Classes

  • Slides: 29
Download presentation
CPE 150: Introduction to Programming Chapter 6: Classes and Data Abstraction Copyright notice: 1

CPE 150: Introduction to Programming Chapter 6: Classes and Data Abstraction Copyright notice: 1 - care has been taken to use only those web images deemed by the instructor to be in the public domain. If you see a copyrighted image on any slide and are the copyright owner, please contact the instructor. It will be removed. 2 - These slides are inspired, based, and modified with permission from the authors of the C++ How to Program (4 th Edition) textbook

Topics To Be Covered In Chapter 6 6. 1 6. 2 6. 3 6.

Topics To Be Covered In Chapter 6 6. 1 6. 2 6. 3 6. 4 6. 5 6. 6 6. 7 6. 8 Introduction Structure Definitions Accessing Structure Members Implementing a User-Defined Type Time with a struct Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members

6. 1 Introduction • Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior)

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

6. 2 Structure Definitions • Structures – Aggregate data types built using elements of

6. 2 Structure Definitions • Structures – Aggregate data types built using elements of other types struct Time { int hour; int minute; int second; }; Structure tag Structure members • Structure member naming – In same struct: must have unique names – In different structs: can share name • struct definition must end with semicolon

6. 2 Structure Definitions • Self-referential structure – Structure member cannot be instance of

6. 2 Structure Definitions • Self-referential structure – Structure member cannot be instance of enclosing struct – Structure member can be pointer to instance of enclosing struct (self-referential structure) • Used for linked lists, queues, stacks and trees • struct definition – Creates new data type used to declare variables – Structure variables declared like variables of other types – Examples: • Time time. Object; time. Array[ 10 ]; *time. Ptr; &time. Ref = time. Object;

6. 3 Accessing Structure Members • Member access operators – Dot operator (. )

6. 3 Accessing Structure Members • Member access operators – Dot operator (. ) for structure and class members – Arrow operator (->) for structure and class members via pointer to object – 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.

6. 4 Implementing a User-Defined Type Time with a struct • Default: structures passed

6. 4 Implementing a User-Defined Type Time with a struct • Default: structures passed by value – Pass structure by reference • Avoid overhead of copying structure • C-style structures – No “interface” • If implementation changes, all programs using that struct must change accordingly – Cannot print as unit • Must print/format member by member – Cannot compare in entirety • Must compare member by member

Dinner will 6. 1: be held at 18: 30: 00 universal time, 1 //

Dinner will 6. 1: be held at 18: 30: 00 universal time, 1 // Fig. fig 06_01. cpp which 6: 30: 00 PM standard 2 // is Create a structure, settime. its members, and print it. 3 #include <iostream> Time with std: : cout; invalid values: 29: 73: 00 5 using 6 using std: : endl; 7 8 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 cout << "Dinner will be held at " ; print. Universal( dinner. Time ); cout << " universal time, nwhich is " ; print. Standard( dinner. Time ); Direct cout << " standard time. n"; access to data allow assignment of bad values. 37 38 dinner. Time. hour = 29; // set hour to invalid value #include <iomanip> 39 dinner. Time. minute = 73; // set minute to invalid value using std: : setfill; Define structure type Time 40 using std: : setw; with three integer members. 41 cout << "n. Time with invalid values: " ; 42 print. Universal( dinner. Time ); // structure definition 43 cout << endl; struct Time { 45 return 0; int hour; // 0 -23 (24 -hour clock format) 47 } // end main int minute; // 0 -59 Use parameterized stream 48 // print time in universal-time format int second; // 0 -59 manipulator setfill. 50 void print. Universal( const Time &t ) Pass references to constant 51 { }; // end struct Time objects to eliminate 52 cout << setfill( '0' ) << setw( 2 ) << t. hour << ": " copying overhead. 53 << setw( 2 ) << t. minute << ": " void print. Universal( const Time & ); // prototype 54 << setw( 2 ) << t. second; void print. Standard( const Time & ); // prototype 56 } // end function print. Universal 58 // print time in standard-time format int main() 59 void print. Standard( const Time &t ) { Use dot operator to initialize 60 { Time dinner. Time; // variable of new type Time structure members. 61 cout << ( ( t. hour == 0 || t. hour == 12 ) ? 62 12 : t. hour % 12 ) << ": " << setfill( '0' ) dinner. Time. hour = 18; // set hour of dinner. Time 63 << setw( 2 ) << t. minute << ": " dinner. Time. minute = 30; // set minute of dinner. Time 64 << setw( 2 ) << t. second dinner. Time. second = 0; // set second of dinner. Time 65 << ( t. hour < 12 ? " AM" : " PM" ); 67 } // end function print. Standard

6. 5 Implementing a Time Abstract Data Type with a class • Classes –

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:

6. 5 Implementing a Time Abstract Data Type with a class • Constructor function

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

1 class Time { 2 3 4 5 6 7 public: Function prototypes for

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

6. 5 Implementing a Time Abstract Data Type with a class • Objects of

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; // // object of type Time array of Time objects pointer to a Time object reference to a Time object

6. 5 Implementing a Time Abstract Data Type with a class • Member functions

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

1 2 3 // Fig. 6. 3: fig 06_03. cpp // Time class. #include

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 22 23 24 25 26 27 29 30 31 32 33 35 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 private: int hour; int minute; int second; // 0 - 23 (24 -hour clock format) // 0 - 59 }; // end class Time 36 37 38 39 40 41 42 43 45 47 48 49 50 51 52 54 56 57 58 59 60 61 62 64 // Time constructor initializes each. Constructor data member to zero and initializes // ensures all Time objects start inprivate a consistent state data members Time: : Time() to 0. { hour = minute = second = 0; } // end Time constructor public member function checks // set new Time value using universal time, perform validity parameter values for // checks on the data values and set invalid values to zero before setting void Time: : set. Time( int h, int m, int s validity ) private data { hour = ( h >= 0 && h < 24 ) ? h : 0; members. minute = ( m >= 0 && m < 60 ) ? m : 0; second = ( s >= 0 && s < 60 ) ? s : 0; } // end function set. Time // print Time in universal format. No arguments (implicitly void Time: : print. Universal() “know” purpose is to print { data members); member cout << setfill( '0' ) << setw( 2 ) << hour << ": " function calls more concise. << setw( 2 ) << minute << ": " << setw( 2 ) << second; } // end function print. Universal // 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" ); } // end function print. Standard

66 67 68 70 71 72 Declare variable t to be int main() {

66 67 68 70 71 72 Declare variable t to be int main() { object of class Time t; // instantiate object t of class Time // output Time object t's initial values cout << "The initial universal time is " ; t. print. Universal(); // 00: 00 73 74 75 Invoke cout << "n. The initial standard time is " ; public member t. print. Standard(); // 12: 00 AM functions to print time. 76 77 t. set. Time( 13, 27, 6 ); 78 79 80 81 // output Time object t's new values public cout << "nn. Universal time after set. Time is " ; 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 93 94 95 97 99 // change time Set data members using member function. Attempt to set data members using public member function. 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 // attempt invalid settings // 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; return 0; } // end main Data members set to 0 after attempting invalid settings.

6. 5 Implementing a Time Abstract Data Type with a class • Destructors –

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”

6. 5 Implementing a Time Abstract Data Type with a class • Advantages of

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

6. 6 Class Scope and Accessing Class Members • Class scope – Data members,

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

6. 6 Class Scope and Accessing Class Members • Function scope – Variables declared

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

6. 6 Class Scope and Accessing Class Members • Operators to access class members

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

1 2 4 5 // Fig. 6. 4: fig 06_04. cpp // Demonstrating the

1 2 4 5 // Fig. 6. 4: fig 06_04. cpp // Demonstrating the class member access via. and -> // CAUTION: IN FUTURE EXAMPLES WE AVOID PUBLIC DATA! #include <iostream> 6 7 8 23 24 25 26 27 int main() { Count counter; // create counter object Count *counter. Ptr = &counter; // create pointer to counter Count &counter. Ref = counter; // reference to counter Usecreate dot member selection using std: : cout; using std: : endl; 9 10 11 // class Count definition class Count { 28 29 30 31 cout << "Assign 1 to x and print using the object's name: " ; counter. x = 1; // assign 1 to data member x Usefunction dot member selection counter. print(); // call member print 12 13 14 15 16 17 18 19 20 21 22 public: int x; void print() { cout << x << endl; } }; // end class Count Data member x public to illustrate class member access operators; typically data members private. operator for counter object. 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 Use arrow member selection counter. Ref. print(); // call member function print 36 37 38 39 cout << "Assign 3 to x and counter. Ptr->x = 3; // assign 3 to data member x counter. Ptr->print(); // call member function print 40 41 return 0; 42 43 operator for counter. Ptr print usingtoa object. pointer: " ; pointer } // 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

6. 7 Separating Interface from Implementation • Separating interface from implementation – Advantage •

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

6. 7 Separating Interface from Implementation • Header files – Class definitions and function

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

time 1. h 1 2 3 // Fig. 6. 5: time 1. h //

time 1. h 1 2 3 // Fig. 6. 5: time 1. h // Declaration of class Time. // Member functions are defined in time 1. cpp 4 5 6 7 // prevent multiple inclusions of header file #ifndef TIME 1_H #define TIME 1_H 8 9 10 // Time abstract data type definition “If class Time { 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 Preprocessor code to prevent multiple inclusions. Code between these directives not defined”Preprocessor directive defines not included if name Naming convention: name TIME 1_H already defined. header file name with underscore replacing period. // 0 - 23 (24 -hour clock format) // 0 - 59

time 1. cpp 1 2 3 // Fig. 6. 6: time 1. cpp //

time 1. cpp 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 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 31 // 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; } // end function set. Time 32 Include header file time 1. h. 33 // print Time in universal format 34 void Time: : print. Universal() 35 { // include definition of class Time from time 1. h 36 cout << setfill( '0' ) << setw( 2 ) << hour << ": " #include "time 1. h" 37 << setw( 2 ) << minute << ": " 38 << setw( 2 ) << second; // Time constructor initializes each data member to zero. 40 } // end function print. Universal // Ensures all Time objects Name start of in header a consistent state. file enclosed Time: : Time() 41 in quotes; angle brackets 42 // print Time in standard format { cause preprocessor to assume 43 void Time: : print. Standard() hour = minute = second = 0; header part of C++ Standard 44 { Library. 45 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) } // end Time constructor 46 << ": " << setfill( '0' ) << setw( 2 ) << minute 47 << ": " << setw( 2 ) << second 48 << ( hour < 12 ? " AM" : " PM" ); 50 } // end function print. Standard

1 2 3 4 // Fig. 6. 7: fig 06_07. cpp // Program to

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 24 25 26 27 28 using std: : cout; using std: : endl; 29 8 9 10 11 12 13 14 // include definition of class Time #include "time 1. h" int main() { Time t; Include header file time 1. h 30 to ensure correct 31 from time 1. h creation/manipulation and 32 33 determine size of Time class 34 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 ); // 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 t. set. Time( 99, 99 ); // attempt invalid settings 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 } // end main // change time 23 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

6. 8 Controlling Access to Members • Access modes – private • Default access

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

6. 8 Controlling Access to Members • Class member access – Default private –

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

1 2 3 4 // Fig. 6. 8: fig 06_08. cpp // Demonstrate errors

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 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 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' Errors produced by attempting to access private members.