1 Lecture 6 Classes and Data Abstraction: Part II.

Slides:



Advertisements
Similar presentations
OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
Advertisements

CPSC 231 C++ Review1 Learning Objectives §Review of the object oriented design goals. §Review of C++ classes l data members l member functions (methods)
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6: Classes and Data Abstraction Outline 6.1 Introduction 6.2 Structure Definitions 6.3 Accessing.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 16: Classes and Data Abstraction Outline 16.1Introduction 16.2Implementing a Time Abstract Data.
Introduction to Classes and Data Abstraction
1 Review (Week2) - Control Structures C++ has only seven control structures: –Sequence structure Programs executed sequentially by default –Selection structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
 2003 Prentice Hall, Inc. All rights reserved Introduction Object-oriented programming (OOP) –Encapsulates data (attributes) and functions (behavior)
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Classi - Esempi1 // SalesPerson class definition // Member functions defined in salesp.cpp #ifndef SALESP_H #define SALESP_H class SalesPerson { public:
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
1 Classes and Data Abstraction Part II Initializing Class Objects: Constructors Constructors  Initialize data members  Same name as class 
1 Chapter 4 CLASSES AND OBJECTS. 2 Outlines Procedural vs. Object ‑ Oriented Programming C++ Structures versus C Structures Classes –Accessing Class Members.
1 Chapter 6 - Functions Outline 6.1Introduction 6.2Program Components in C++ 6.6Math Library Functions 6.4Functions 6.5Function Definitions 6.6Function.
SMIE-121 Software Design II School of Mobile Information Engineering, Sun Yat-sen University Lecture.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
1 Classes and Data Abstraction Part I Introduction Object-oriented programming (OOP)  Encapsulates data (attributes) and functions (behavior)
1 C++ Classes: Access (II) Ying Wu Electrical Engineering & Computer Science Northwestern University ECE230 Lectures Series.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 6: Classes and Data Abstraction Outline 6.1Introduction 6.2Structure Definitions 6.3Accessing.
CLASSES : A DEEPER LOOK Chapter 9 Part I 1. 2 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition.
Chapter 9 Classes: A Deeper Look, Part I Part II.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 23 November 19, 2009.
 In this chapter you ‘’ll learn: ◦ To construct programs modularly from functions ◦ To use common math library functions ◦ The mechanism for passing.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Class 3 (L33) u Client of a Class u Purpose of Public Members u Private Class Members u Controlling Access u Access Functions u Predicate Functions u Utility.
Structures (L30) u Syntax of a struct Declaration u Structure Variables u Accessing Members of Structures u Initialize Structure Variables u Array of Structures.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3: Classes May 24,
Class 4 (L34) u Constructors u Default Constructor u Example of Default Constructors u Destructors u Constructors Are Called in Global Scope u Constructors.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 4: Classes Jan 27,
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 6: Classes and Data Abstraction Posted Feb 3 Chapter 6 pointer for function Class Introduction.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 20 November 10, 2009.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
EC-111 Algorithms & Computing Lecture #6 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 7: Classes Part II Outline 7.1 Introduction 7.2 const (Constant) Objects and const Member Functions.
C++ Programming Lecture 12 Functions – Part IV
 2000 Prentice Hall, Inc. All rights reserved. NHTI CP 107 Fall 2001 M. Saleem Yusuf Introduction Object-oriented programming (OOP) –Objects Encapsulates.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Review slides Mar 15, 2005.
 2003 Prentice Hall, Inc. All rights reserved. ECE 2552 Dr. Këpuska Summer 2004 from Dr. S. Kozaitis Spring 2003 slides 1 Summary of Chapter 6: Classes.
1 Example Original Array Array After 2 nd Pass Array After 1 st Pass Array After 3 rd Pass.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Jan 20, 2004.
Chapter 15 - C++ As A "Better C"
Chapter 16: Classes and Data Abstraction
Classes and Data Abstraction
Chapter 16: Classes and Data Abstraction
Classes: A Deeper Look Outline
Lecture 5: Classes September 14, 2004
Chapter 6: Classes and Data Abstraction
Chapter 9 Classes: A Deeper Look, Part 1
Chapter 6: Classes and Data Abstraction
Object-oriented programming (OOP)
Chapter 6: Classes and Data Abstraction
Variables have attributes
Chapter 15 - C++ As A "Better C"
CISC181 Introduction to Computer Science Dr
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Classes: A Deeper Look, Part 1
Chapter 6: Classes and Data Abstraction
Chapter 6: Classes and Data Abstraction
More C++ Classes Systems Programming.
Presentation transcript:

1 Lecture 6 Classes and Data Abstraction: Part II

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

3 6.2 Structure Definitions struct definition  Creates new data type used to declare variables  Structure variables declared like variables of other types  Examples: Time timeObject; Time timeArray[ 10 ]; struct vs. class  One difference By default everything in struct is public By default everything in class is private  Practical difference Generally, struct only has data, no methods Class has both data and methods

4 6.3 Accessing Structure Members Member access operators  Dot operator (. ) for structure and class members  Print member hour of timeObject : cout << timeObject.hour;

5 3.17References and Reference Parameters Call by value  Copy of data passed to function  Changes to copy do not change original  Prevent unwanted side effects Call by reference  Function can directly access data  Changes affect original

6 3.17References and Reference Parameters Reference parameter  Alias for argument in function call Passes parameter by reference  Use & after data type in prototype void myFunction( int &data ) Read “ data is a reference to an int ”  Function call format the same However, original can now be changed

7 fig03_20.cpp (1 of 2) 1 // Fig. 3.20: fig03_20.cpp 2 // Comparing pass-by-value and pass-by-reference 3 // with references. 4 #include 5 6 using std::cout; 7 using std::endl; 8 9 int squareByValue( int ); // function prototype 10 void squareByReference( int & ); // function prototype int main() 13 { 14 int x = 2; 15 int z = 4; // demonstrate squareByValue 18 cout << "x = " << x << " before squareByValue\n"; 19 cout << "Value returned by squareByValue: " 20 << squareByValue( x ) << endl; 21 cout << "x = " << x << " after squareByValue\n" << endl; 22

8 fig03_20.cpp (2 of 2) 23 // demonstrate squareByReference 24 cout << "z = " << z << " before squareByReference" << endl; 25 squareByReference( z ); 26 cout << "z = " << z << " after squareByReference" << endl; return 0; // indicates successful termination 29 } // end main // squareByValue multiplies number by itself, stores the 32 // result in number and returns the new value of number 33 int squareByValue( int number ) 34 { 35 return number *= number; // caller's argument not modified } // end function squareByValue // squareByReference multiplies numberRef by itself and 40 // stores the result in the variable to which numberRef 41 // refers in function main 42 void squareByReference( int &numberRef ) 43 { 44 numberRef *= numberRef; // caller's argument modified } // end function squareByReference

9 fig03_20.cpp output (1 of 1) x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue z = 4 before squareByReference z = 16 after squareByReference

References and Reference Parameters Pointers (chapter 5)  Another way to pass-by-reference References as aliases to other variables  Refer to same variable  Can be used within a function int count = 1; // declare integer variable count int &cRef = count; // create cRef as an alias for count ++cRef; // increment count (using its alias) References must be initialized when declared  Otherwise, compiler error  Dangling reference Reference to undefined variable

11 fig03_21.cpp (1 of 1) 1 // Fig. 3.21: fig03_21.cpp 2 // References must be initialized. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 3; // y refers to (is an alias for) x 13 int &y = x; cout << "x = " << x << endl << "y = " << y << endl; 16 y = 7; 17 cout << "x = " << x << endl << "y = " << y << endl; return 0; // indicates successful termination } // end main

12 x = 3 y = 3 x = 7 y = 7 fig03_21.cpp output (1 of 1)

13 fig03_22.cpp (1 of 1) 1 // Fig. 3.22: fig03_22.cpp 2 // References must be initialized. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 3; 11 int &y; // Error: y must be initialized cout << "x = " << x << endl << "y = " << y << endl; 14 y = 7; 15 cout << "x = " << x << endl << "y = " << y << endl; return 0; // indicates successful termination } // end main

14 Borland C++ command-line compiler error message: Error E2304 Fig03_22.cpp 11: Reference variable 'y' must be initialized ­ in function main() Microsoft Visual C++ compiler error message: D:\cpphtp4_examples\ch03\Fig03_22.cpp(11 ) : error C2530: 'y' : references must be initialized fig03_22.cpp output (1 of 1)

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

16 fig06_01.cpp (1 of 4) 1 // Fig. 6.1: fig06_01.cpp 2 // Create a structure, set its members, and print it. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::setfill; 11 using std::setw; // structure definition 14 struct Time { 15 int hour; // 0-23 (24-hour clock format) 16 int minute; // int second; // }; // end struct Time 20

17 fig06_01.cpp (2 of 4) 21 void printUniversal( const Time & ); // prototype 22 void printStandard( const Time & ); // prototype int main() 25 { 26 Time dinnerTime; // variable of new type Time dinnerTime.hour = 18; // set hour member of dinnerTime 29 dinnerTime.minute = 30; // set minute member of dinnerTime 30 dinnerTime.second = 0; // set second member of dinnerTime cout << "Dinner will be held at "; 33 printUniversal( dinnerTime ); 34 cout << " universal time,\nwhich is "; 35 printStandard( dinnerTime ); 36 cout << " standard time.\n"; dinnerTime.hour = 29; // set hour to invalid value 39 dinnerTime.minute = 73; // set minute to invalid value

18 fig06_01.cpp (3 of 4) cout << "\nTime with invalid values: "; 42 printUniversal( dinnerTime ); 43 cout << endl; return 0; } // end main // print time in universal-time format 50 void printUniversal( const Time &t ) 51 { 52 cout << setfill( '0' ) << setw( 2 ) << t.hour << ":" 53 << setw( 2 ) << t.minute << ":" 54 << setw( 2 ) << t.second; } // end function printUniversal 57

19 fig06_01.cpp (4 of 4) fig06_01.cpp output (1 of 1) 58 // print time in standard-time format 59 void printStandard( const Time &t ) 60 { 61 cout << ( ( t.hour == 0 || t.hour == 12 ) ? : t.hour % 12 ) << ":" << setfill( '0' ) 63 << setw( 2 ) << t.minute << ":" 64 << setw( 2 ) << t.second 65 << ( t.hour < 12 ? " AM" : " PM" ); } // end function printStandard Dinner will be held at 18:30:00 universal time, which is 6:30:00 PM standard time. Time with invalid values: 29:73:00

Controlling Access to Members Access modes  private Default access mode Accessible to member functions and friend s  public Accessible to any function in program with handle to class object  protected Chapter 9

21 time1.h (1 of 1) 1 // Fig. 6.5: time1.h 2 // Declaration of class Time. 3 // Member functions are defined in time1.cpp 4 5 // prevent multiple inclusions of header file 6 #ifndef TIME1_H 7 #define TIME1_H 8 9 // Time abstract data type definition 10 class Time { 11 public: 12 Time(); // constructor 13 void setTime( int, int, int ); // set hour, minute, second 14 void printUniversal(); // print universal-time format 15 void printStandard(); // print standard-time format private: 18 int hour; // (24-hour clock format) 19 int minute; // int second; // }; // end class Time #endif

22 fig06_08.cpp (1 of 1) 1 // Fig. 6.8: fig06_08.cpp 2 // Demonstrate errors resulting from attempts 3 // to access private class members. 4 #include 5 6 using std::cout; 7 8 // include definition of class Time from time1.h 9 #include "time1.h" int main() 12 { 13 Time t; // create Time object t.hour = 7; // error: 'Time::hour' is not accessible // error: 'Time::minute' is not accessible 19 cout << "minute = " << t.minute; return 0; } // end main

23 fig06_08.cpp output (1 of 1) D:\cpphtp4_examples\ch06\Fig6_06\Fig06_06.cpp(16) : error C2248: 'hour' : cannot access private member declared in class 'Time' D:\cpphtp4_examples\ch06\Fig6_06\Fig06_06.cpp(19) : error C2248: 'minute' : cannot access private member declared in class 'Time'

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

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

26 Static Functions Functions associated with a class but do not need access to any data  Function is declared static in header file Associated with class, but not an instance of the class  Example In MyDate.h static int daysInMonth(Months mon, int yr); In MyDate.cpp int MyDate::daysInMonth(Months mon, int yr) {…} When calling method int day = MyDate::daysInMonth(month, year);

27 salesp.h (1 of 1) 1 // Fig. 6.9: salesp.h 2 // SalesPerson class definition. 3 // Member functions defined in salesp.cpp. 4 #ifndef SALESP_H 5 #define SALESP_H 6 7 class SalesPerson { 8 9 public: 10 SalesPerson(); // constructor 11 void getSalesFromUser(); // input sales from keyboard 12 void setSales( int, double ); // set sales for a month 13 void printAnnualSales(); // summarize and print sales private: 16 double totalAnnualSales(); // utility function 17 double sales[ 12 ]; // 12 monthly sales figures }; // end class SalesPerson #endif

28 salesp.cpp (1 of 3) 1 // Fig. 6.10: salesp.cpp 2 // Member functions for class SalesPerson. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 using std::fixed; 9 10 #include using std::setprecision; // include SalesPerson class definition from salesp.h 15 #include "salesp.h" // initialize elements of array sales to SalesPerson::SalesPerson() 19 { 20 for ( int i = 0; i < 12; i++ ) 21 sales[ i ] = 0.0; } // end SalesPerson constructor 24

29 salesp.cpp (2 of 3) 25 // get 12 sales figures from the user at the keyboard 26 void SalesPerson::getSalesFromUser() { 27 double salesFigure; for ( int i = 1; i <= 12; i++ ) { 30 cout << "Enter sales amount for month " << i << ": "; 31 cin >> salesFigure; 32 setSales( i, salesFigure ); 33 } // end for 34 } // end function getSalesFromUser // set one of the 12 monthly sales figures; function subtracts 37 // one from month value for proper subscript in sales array 38 void SalesPerson::setSales( int month, double amount ) 39 { 40 // test for valid month and amount values 41 if ( month >= 1 && month 0 ) 42 sales[ month - 1 ] = amount; // adjust for subscripts else // invalid month or amount value 45 cout << "Invalid month or sales figure" << endl; 46 } // end function setSales

30 salesp.cpp (3 of 3) 47 // print total annual sales (with help of utility function) 48 void SalesPerson::printAnnualSales() { 49 cout << setprecision( 2 ) << fixed 50 << "\nThe total annual sales are: $" 51 << totalAnnualSales() << endl; // call utility function } // end function printAnnualSales // private utility function to total annual sales 56 double SalesPerson::totalAnnualSales() { 57 double total = 0.0; // initialize total for ( int i = 0; i < 12; i++ ) // summarize sales results 60 total += sales[ i ]; return total; } // end function totalAnnualSales

31 fig06_11.cpp (1 of 1) 1 // Fig. 6.11: fig06_11.cpp 2 // Demonstrating a utility function. 3 // Compile this program with salesp.cpp 4 5 // include SalesPerson class definition from salesp.h 6 #include "salesp.h" 7 8 int main() 9 { 10 SalesPerson s; // create SalesPerson object s s.getSalesFromUser(); // note simple sequential code; no 13 s.printAnnualSales(); // control structures in main return 0; } // end main

32 fig06_11.cpp output (1 of 1) Enter sales amount for month 1: Enter sales amount for month 2: Enter sales amount for month 3: Enter sales amount for month 4: Enter sales amount for month 5: Enter sales amount for month 6: Enter sales amount for month 7: Enter sales amount for month 8: Enter sales amount for month 9: Enter sales amount for month 10: Enter sales amount for month 11: Enter sales amount for month 12: The total annual sales are: $

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  No explicit destructor Compiler creates “empty” destructor”

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

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

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

37 create.h (1 of 1) 1 // Fig. 6.15: create.h 2 // Definition of class CreateAndDestroy. 3 // Member functions defined in create.cpp. 4 #include 5 #ifndef CREATE_H 6 #define CREATE_H 7 8 class CreateAndDestroy { 9 10 public: 11 CreateAndDestroy( int, string ); // constructor 12 ~CreateAndDestroy(); // destructor private: 15 int objectID; 16 string message; }; // end class CreateAndDestroy #endif

38 create.cpp (1 of 2) 1 // Fig. 6.16: create.cpp 2 // Member-function definitions for class CreateAndDestroy 3 #include 5 using std::cout; 6 using std::endl; 7 8 // include CreateAndDestroy class definition from create.h 9 #include "create.h" // constructor 12 CreateAndDestroy::CreateAndDestroy( 13 int objectNumber, string messageStr ) 14 { 15 objectID = objectNumber; 16 message = messageStr; cout << "Object " << objectID << " constructor runs " 19 << message << endl; } // end CreateAndDestroy constructor

39 create.cpp (2 of 2) 23 // destructor 24 CreateAndDestroy::~CreateAndDestroy() 25 { 26 // the following line is for pedagogic purposes only 27 cout << ( objectID == 1 || objectID == 6 ? "\n" : "" ); cout << "Object " << objectID << " destructor runs " 30 << message << endl; } // end ~CreateAndDestroy destructor

40 fig06_17.cpp (1 of 3) 1 // Fig. 6.17: fig06_17.cpp 2 // Demonstrating the order in which constructors and 3 // destructors are called. 4 #include 5 using std::cout; 6 using std::endl; 7 8 // include CreateAndDestroy class definition from create.h 9 #include "create.h" void create( void ); // prototype 12 // global object 13 CreateAndDestroy first( 1, "(global before main)" ); int main() { 16 cout << "\nMAIN FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy second( 2, "(local automatic in main)" ); 19 static CreateAndDestroy third( 3, "(local static in main)" );

41 fig06_17.cpp (2 of 3) 20 create(); // call function to create objects cout << "\nMAIN FUNCTION: EXECUTION RESUMES" << endl; 23 CreateAndDestroy fourth( 4, "(local automatic in main)" ); cout << "\nMAIN FUNCTION: EXECUTION ENDS" << endl; 26 return 0; 27 } // end main // function to create objects 30 void create( void ) { 31 cout << "\nCREATE FUNCTION: EXECUTION BEGINS" << endl; CreateAndDestroy fifth( 5, "(local automatic in create)" ); 34 static CreateAndDestroy sixth( 6, "(local static in create)" ); 38 CreateAndDestroy seventh( 7, "(local automatic in create)" ); cout << "\nCREATE FUNCTION: EXECUTION ENDS" << endl; } // end function create

42 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 FUNCTION: EXECUTION BEGINS Object 5 constructor runs (local automatic in create) Object 6 constructor runs (local static in create) Object 7 constructor runs (local automatic in create) CREATE FUNCTION: EXECUTION ENDS Object 7 destructor runs (local automatic in create) Object 5 destructor runs (local automatic in create) MAIN FUNCTION: EXECUTION RESUMES Object 4 constructor runs (local automatic in main) MAIN FUNCTION: EXECUTION ENDS Object 4 destructor runs (local automatic in main) Object 2 destructor runs (local automatic in main) Object 6 destructor runs (local static in create) Object 3 destructor runs (local static in main) Object 1 destructor runs (global before main) fig06_17.cpp output (1 of 1)

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

44 fig06_24.cpp (1 of 3) 1 // Fig. 6.24: fig06_24.cpp 2 // Demonstrating that class objects can be assigned 3 // to each other using default memberwise assignment. 4 #include 5 using std::cout; 6 using std::endl; 7 8 // class Date definition 9 class Date { 10 public: 11 Date( int = 1, int = 1, int = 1990 ); // default constructor 12 void print(); private: 15 int month; 16 int day; 17 int year; }; // end class Date 20

45 fig06_24.cpp (2 of 3) 21 // Date constructor with no range checking 22 Date::Date( int m, int d, int y ) { 23 month = m; 24 day = d; 25 year = y; } // end Date constructor // print Date in the format mm-dd-yyyy 30 void Date::print() { 31 cout << month << '-' << day << '-' << year; } // end function print int main() { 36 Date date1( 7, 4, 2002 ); 37 Date date2; // date2 defaults to 1/1/

46 fig06_24.cpp (3 of 3) fig06_24.cpp output (1 of 1) 44 cout << "date1 = "; 45 date1.print(); 46 cout << "\ndate2 = "; 47 date2.print(); date2 = date1; // default memberwise assignment cout << "\n\nAfter default memberwise assignment, date2 = "; 52 date2.print(); 53 cout << endl; return 0; } // end main date1 = date2 = After default memberwise assignment, date2 =

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

48 Constants Constants should be inside classes when appropriate  Prevents pollution of namespace Declaring constants  In header file static const ; Example: static const char REFERENCE_PREFIX;  In.cpp file const :: = ; Example: const char LibraryBook::REFERENCE_PREFIX = 'R';  Using constant :: Example: LibraryBook::REFERENCE_PREFIX

49 Objects as Parameters Special case when you pass an object that is the same type as the class  Have access to all the private data of both objects Object method was invoked on (i.e. book1 if you called book1.method() ) Object that was passed as a parameter  Object method invoked on is called this Save it in a variable  obj = *this;  Reference private date with.

50 Example: Pass Object as Parameter Want a method that reports which line is steeper between two Line2D s  One line is steeper if its slope is larger bool Line2D::isSteeper(const Line2D& other) { Line2D& obj = *this; if (obj.slope > other.slope) return true; else return false; }