 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Review slides Mar 15, 2005.

Slides:



Advertisements
Similar presentations
Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3.
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
Pointers and Strings. Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close relationship with arrays and strings.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 7 - Pointers Outline 7.1Introduction 7.2Pointer Variable Declarations and Initialization 7.3Pointer.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
1 Lecture Note 7- Classes Part II Outline Composition: Objects as Members of Classes Dynamic Memory static Class Members Operator Overloading.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Classes: A Deeper Look Systems Programming.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 3 Arrays & Pointers.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 4 - Classes Jan 27,
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
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.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades.
(continue) © by Pearson Education, Inc. All Rights Reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Pointers.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
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.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
 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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
C++ Programming Lecture 18 Pointers – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
IS Program Design and Software Tools Introduction to C++ Programming
Lecture 5: Classes (continued) Feb 1, 2005
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
CSC113: Computer Programming (Theory = 03, Lab = 01)
CSC113: Computer Programming (Theory = 03, Lab = 01)
Remark: Data Type of Array Name
Operator Overloading; String and Array Objects
Operator Overloading.
Arrays Kingdom of Saudi Arabia
Operator Overloading; String and Array Objects
7.4 friend Functions and friend Classes
Operator Overloading.
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Recitation Course 0520 Speaker: Liu Yu-Jiun.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Lecture 2 Arrays & Pointers May 17, 2004
Chapter 18 - Operator Overloading
Lecture 2 Arrays & Pointers September 7, 2004
CISC181 Introduction to Computer Science Dr
More C++ Classes Systems Programming.
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

 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. 2 Review topics 1.Lvalue/rvalue 2.Reference variable + Calling functions by reference 3.Passing arrays to functions 4.Function pointers 5.Arrays of pointers to functions (e.g. menus) 6.Using member selection operators ('.' '->') 7.Returning a reference to a private data member 8.*this pointer 1.implicit & explicit use of *this pointer 2.*this pointer & cascaded function calls 9.When are destructors used, why not yet in the classes we're creating? 10.When is it appropriate to use 'new' and 'delete' from the library? 11.Classes? 12.Polymorphism? 13.Multiple Inheritance?

 2003 Prentice Hall, Inc. All rights reserved. 3 Confusing Equality (==) and Assignment (=) Operators Lvalues –Expressions that can appear on left side of equation –Can be changed x = 4; Rvalues –Only appear on right side of equation –Constants, such as numbers (i.e. cannot write 4 = x; ) Lvalues can be used as rvalues, but not vice versa

 2003 Prentice Hall, Inc. All rights reserved. 4 References 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 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

 2003 Prentice Hall, Inc. All rights reserved. 5 References and Reference Parameters Pointers –Another way to pass-by-refernce 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

 2003 Prentice Hall, Inc. All rights reserved. 6 Passing Arrays to Functions Specify name without brackets –To pass array myArray to myFunction int myArray[ 24 ]; myFunction( myArray, 24 ); –Array size usually passed, but not required Useful to iterate over all elements Arrays passed-by-reference –Functions can modify original array data –Value of name of array is address of first element Function knows where the array is stored Can change original memory locations

 2003 Prentice Hall, Inc. All rights reserved. 7 Passing Arrays to Functions Functions taking arrays –Function prototype void modifyArray( int b[], int arraySize ); void modifyArray( int [], int ); –Names optional in prototype Both take an integer array and a single integer –No need for array size between brackets Ignored by compiler –If declare array parameter as const Cannot be modified (compiler error) void doNotModify( const int [] );

 2003 Prentice Hall, Inc. All rights reserved. 8 Using const with Pointers const qualifier –Value of variable should not be modified –const used when function does not need to change a variable –Principle of least privilege const pointers –Always point to same memory location –Default for array name –Must be initialized when declared Four ways to pass pointer to function –Nonconstant pointer to nonconstant data Highest amount of access –Nonconstant pointer to constant data –Constant pointer to nonconstant data –Constant pointer to constant data Least amount of access

 2003 Prentice Hall, Inc. All rights reserved. Outline 9 fig05_13.cpp (1 of 1) fig05_13.cpp output (1 of 1) 1 // Fig. 5.13: fig05_13.cpp 2 // Attempting to modify a constant pointer to 3 // non-constant data. 4 5 int main() 6 { 7 int x, y; 8 9 // ptr is a constant pointer to an integer that can 10 // be modified through ptr, but ptr always points to the 11 // same memory location. 12 int * const ptr = &x; *ptr = 7; // allowed: *ptr is not const 15 ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main d:\cpphtp4_examples\ch05\Fig05_13.cpp(15) : error C2166: l-value specifies const object ptr is constant pointer to integer. Can modify x (pointed to by ptr ) since x not constant. Cannot modify ptr to point to new address since ptr is constant. Line 15 generates compiler error by attempting to assign new address to constant pointer.

 2003 Prentice Hall, Inc. All rights reserved. Outline 10 fig05_14.cpp (1 of 1) 1 // Fig. 5.14: fig05_14.cpp 2 // Attempting to modify a constant pointer to constant data. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 5, y; // ptr is a constant pointer to a constant integer. 13 // ptr always points to the same location; the integer 14 // at that location cannot be modified. 15 const int *const ptr = &x; cout << *ptr << endl; *ptr = 7; // error: *ptr is const; cannot assign new value 20 ptr = &y; // error: ptr is const; cannot assign new address return 0; // indicates successful termination } // end main ptr is constant pointer to integer constant. Cannot modify x (pointed to by ptr ) since *ptr declared constant. Cannot modify ptr to point to new address since ptr is constant.

 2003 Prentice Hall, Inc. All rights reserved. 11 Relationship Between Pointers and Arrays Arrays and pointers closely related –Array name like constant pointer –Pointers can do array subscripting operations Accessing array elements with pointers –Element b[ n ] can be accessed by *( bPtr + n ) Called pointer/offset notation –Addresses &b[ 3 ] same as bPtr + 3 –Array name can be treated as pointer b[ 3 ] same as *( b + 3 ) –Pointers can be subscripted (pointer/subscript notation) bPtr[ 3 ] same as b[ 3 ]

 2003 Prentice Hall, Inc. All rights reserved. 12 Function Pointers Calling functions using pointers –Assume parameter: bool ( *compare ) ( int, int ) –Execute function with either ( *compare ) ( int1, int2 ) –Dereference pointer to function to execute OR compare( int1, int2 ) –Could be confusing User may think compare name of actual function in program

 2003 Prentice Hall, Inc. All rights reserved. Outline 13 fig05_25.cpp (1 of 5) 1 // Fig. 5.25: fig05_25.cpp 2 // Multipurpose sorting program using function pointers. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include using std::setw; // prototypes 14 void bubble( int [], const int, bool (*)( int, int ) ); 15 void swap( int * const, int * const ); 16 bool ascending( int, int ); 17 bool descending( int, int ); int main() 20 { 21 const int arraySize = 10; 22 int order; 23 int counter; 24 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 25 Parameter is pointer to function that receives two integer parameters and returns bool result.

 2003 Prentice Hall, Inc. All rights reserved. Outline 14 fig05_25.cpp (2 of 5) 26 cout << "Enter 1 to sort in ascending order,\n" 27 << "Enter 2 to sort in descending order: "; 28 cin >> order; 29 cout << "\nData items in original order\n"; // output original array 32 for ( counter = 0; counter < arraySize; counter++ ) 33 cout << setw( 4 ) << a[ counter ]; // sort array in ascending order; pass function ascending 36 // as an argument to specify ascending sorting order 37 if ( order == 1 ) { 38 bubble( a, arraySize, ascending ); 39 cout << "\nData items in ascending order\n"; 40 } // sort array in descending order; pass function descending 43 // as an agrument to specify descending sorting order 44 else { 45 bubble( a, arraySize, descending ); 46 cout << "\nData items in descending order\n"; 47 } 48

 2003 Prentice Hall, Inc. All rights reserved. Outline 15 fig05_25.cpp (3 of 5) 49 // output sorted array 50 for ( counter = 0; counter < arraySize; counter++ ) 51 cout << setw( 4 ) << a[ counter ]; cout << endl; return 0; // indicates successful termination } // end main // multipurpose bubble sort; parameter compare is a pointer to 60 // the comparison function that determines sorting order 61 void bubble( int work[], const int size, 62 bool (*compare)( int, int ) ) 63 { 64 // loop to control passes 65 for ( int pass = 1; pass < size; pass++ ) // loop to control number of comparisons per pass 68 for ( int count = 0; count < size - 1; count++ ) // if adjacent elements are out of order, swap them 71 if ( (*compare)( work[ count ], work[ count + 1 ] ) ) 72 swap( &work[ count ], &work[ count + 1 ] ); compare is pointer to function that receives two integer parameters and returns bool result. Parentheses necessary to indicate pointer to function Call passed function compare ; dereference pointer to execute function.

 2003 Prentice Hall, Inc. All rights reserved. Outline 16 fig05_25.cpp (4 of 5) } // end function bubble // swap values at memory locations to which 77 // element1Ptr and element2Ptr point 78 void swap( int * const element1Ptr, int * const element2Ptr ) 79 { 80 int hold = *element1Ptr; 81 *element1Ptr = *element2Ptr; 82 *element2Ptr = hold; } // end function swap // determine whether elements are out of order 87 // for an ascending order sort 88 bool ascending( int a, int b ) 89 { 90 return b < a; // swap if b is less than a } // end function ascending 93

 2003 Prentice Hall, Inc. All rights reserved. Outline 17 fig05_25.cpp (5 of 5) fig05_25.cpp output (1 of 1) 94 // determine whether elements are out of order 95 // for a descending order sort 96 bool descending( int a, int b ) 97 { 98 return b > a; // swap if b is greater than a } // end function descending Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 1 Data items in original order Data items in ascending order Enter 1 to sort in ascending order, Enter 2 to sort in descending order: 2 Data items in original order Data items in descending order

 2003 Prentice Hall, Inc. All rights reserved. 18 Function Pointers Arrays of pointers to functions –Menu-driven systems –Pointers to each function stored in array of pointers to functions All functions must have same return type and same parameter types –Menu choice  subscript into array of function pointers

 2003 Prentice Hall, Inc. All rights reserved. Outline 19 fig05_26.cpp (1 of 3) 1 // Fig. 5.26: fig05_26.cpp 2 // Demonstrating an array of pointers to functions. 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 // function prototypes 10 void function1( int ); 11 void function2( int ); 12 void function3( int ); int main() 15 { 16 // initialize array of 3 pointers to functions that each 17 // take an int argument and return void 18 void (*f[ 3 ])( int ) = { function1, function2, function3 }; int choice; cout << "Enter a number between 0 and 2, 3 to end: "; 23 cin >> choice; 24 Array initialized with names of three functions; function names are pointers.

 2003 Prentice Hall, Inc. All rights reserved. Outline 20 fig05_26.cpp (2 of 3) 25 // process user's choice 26 while ( choice >= 0 && choice < 3 ) { // invoke function at location choice in array f 29 // and pass choice as an argument 30 (*f[ choice ])( choice ); cout << "Enter a number between 0 and 2, 3 to end: "; 33 cin >> choice; 34 } cout << "Program execution completed." << endl; return 0; // indicates successful termination } // end main void function1( int a ) 43 { 44 cout << "You entered " << a 45 << " so function1 was called\n\n"; } // end function1 48 Call chosen function by dereferencing corresponding element in array.

 2003 Prentice Hall, Inc. All rights reserved. Outline 21 fig05_26.cpp (3 of 3) fig05_26.cpp output (1 of 1) 49 void function2( int b ) 50 { 51 cout << "You entered " << b 52 << " so function2 was called\n\n"; } // end function void function3( int c ) 57 { 58 cout << "You entered " << c 59 << " so function3 was called\n\n"; } // end function3 Enter a number between 0 and 2, 3 to end: 0 You entered 0 so function1 was called Enter a number between 0 and 2, 3 to end: 1 You entered 1 so function2 was called Enter a number between 0 and 2, 3 to end: 2 You entered 2 so function3 was called Enter a number between 0 and 2, 3 to end: 3 Program execution completed.

 2003 Prentice Hall, Inc. All rights reserved. 22 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 timeObject : cout << timeObject.hour; OR timePtr = &timeObject; cout hour; –timePtr->hour same as ( *timePtr ).hour Parentheses required –* lower precedence than.

 2003 Prentice Hall, Inc. All rights reserved. 23 Subtle Trap: Returning a Reference to a private Data Member Reference to object –&pRef = p; –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. Outline 24 time4.h (1 of 1) 1 // Fig. 6.21: time4.h 2 // Declaration of class Time. 3 // Member functions defined in time4.cpp 4 5 // prevent multiple inclusions of header file 6 #ifndef TIME4_H 7 #define TIME4_H 8 9 class Time { public: 12 Time( int = 0, int = 0, int = 0 ); 13 void setTime( int, int, int ); 14 int getHour(); int &badSetHour( int ); // DANGEROUS reference return private: 19 int hour; 20 int minute; 21 int second; }; // end class Time #endif Function to demonstrate effects of returning reference to private data member.

 2003 Prentice Hall, Inc. All rights reserved. Outline 25 time4.cpp (2 of 2) 25 // return hour value 26 int Time::getHour() 27 { 28 return hour; } // end function getHour // POOR PROGRAMMING PRACTICE: 33 // Returning a reference to a private data member. 34 int &Time::badSetHour( int hh ) 35 { 36 hour = ( hh >= 0 && hh < 24 ) ? hh : 0; return hour; // DANGEROUS reference return } // end function badSetHour Return reference to private data member hour.

 2003 Prentice Hall, Inc. All rights reserved. Outline 26 fig06_23.cpp (1 of 2) 1 // Fig. 6.23: fig06_23.cpp 2 // Demonstrating a public member function that 3 // returns a reference to a private data member. 4 #include 5 6 using std::cout; 7 using std::endl; 8 9 // include definition of class Time from time4.h 10 #include "time4.h" int main() 13 { 14 Time t; // store in hourRef the reference returned by badSetHour 17 int &hourRef = t.badSetHour( 20 ); cout << "Hour before modification: " << hourRef; // use hourRef to set invalid value in Time object t 22 hourRef = 30; cout << "\nHour after modification: " << t.getHour(); 25 badSetHour returns reference to private data member hour. Reference allows setting of private data member hour.

 2003 Prentice Hall, Inc. All rights reserved. Outline 27 fig06_23.cpp (2 of 2) fig06_23.cpp output (1 of 1) 26 // Dangerous: Function call that returns 27 // a reference can be used as an lvalue! 28 t.badSetHour( 12 ) = 74; cout << "\n\n*********************************\n" 31 << "POOR PROGRAMMING PRACTICE!!!!!!!!\n" 32 << "badSetHour as an lvalue, Hour: " 33 << t.getHour() 34 << "\n*********************************" << endl; return 0; } // end main Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 ********************************* Can use function call as lvalue to set invalid value. Returning reference allowed invalid setting of private data member hour.

 2003 Prentice Hall, Inc. All rights reserved. 28 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. 29 Dynamic Memory Management with Operators new and delete Dynamic memory management –Control allocation and deallocation of memory –Operators new and delete Include standard header new Time *timePtr; timePtr = new Time; –Creates object of proper size for type Time Error if no space in memory for object –Calls default constructor for object –Returns pointer of specified type –Providing initializers double *ptr = new double( ); Time *timePtr = new Time( 12, 0, 0 ); –Allocating arrays int *gradesArray = new int[ 10 ];

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

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

 2003 Prentice Hall, Inc. All rights reserved. 32 static Class Members Accessing static class variables –Accessible through any object of class –public static variables Can also be accessed using binary scope resolution operator( :: ) Employee::count –private static variables When no class member objects exist: Can only be accessed via public static member function Employee::getCount() static member functions –Cannot access non- static data or functions –No this pointer for static functions static data members and static member functions exist independent of objects

 2003 Prentice Hall, Inc. All rights reserved. Outline 33 employee2.h (1 of 2) 1 // Fig. 7.17: employee2.h 2 // Employee class definition. 3 #ifndef EMPLOYEE2_H 4 #define EMPLOYEE2_H 5 6 class Employee { 7 8 public: 9 Employee( const char *, const char * ); // constructor 10 ~Employee(); // destructor 11 const char *getFirstName() const; // return first name 12 const char *getLastName() const; // return last name // static member function 15 static int getCount(); // return # objects instantiated private: 18 char *firstName; 19 char *lastName; // static data member 22 static int count; // number of objects instantiated }; // end class Employee 25 static member function can only access static data members and member functions. static data member is class-wide data.

 2003 Prentice Hall, Inc. All rights reserved. Outline 34 employee2.h (2 of 2) employee2.cpp (1 of 3) 26 #endif 1 // Fig. 7.18: employee2.cpp 2 // Member-function definitions for class Employee. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include // C++ standard new operator 9 #include // strcpy and strlen prototypes #include "employee2.h" // Employee class definition // define and initialize static data member 14 int Employee::count = 0; // define static member function that returns number of 17 // Employee objects instantiated 18 int Employee::getCount() 19 { 20 return count; } // end static function getCount Initialize static data member exactly once at file scope. static member function accesses static data member count.

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

 2003 Prentice Hall, Inc. All rights reserved. Outline 36 employee2.cpp (3 of 3) 48 delete [] firstName; // recapture memory 49 delete [] lastName; // recapture memory count; // decrement static count of employees } // end destructor ~Employee // return first name of employee 56 const char *Employee::getFirstName() const 57 { 58 // const before return type prevents client from modifying 59 // private data; client should copy returned string before 60 // destructor deletes storage to prevent undefined pointer 61 return firstName; } // end function getFirstName // return last name of employee 66 const char *Employee::getLastName() const 67 { 68 // const before return type prevents client from modifying 69 // private data; client should copy returned string before 70 // destructor deletes storage to prevent undefined pointer 71 return lastName; } // end function getLastName Operator delete deallocates memory. Use static data member to store total count of employees.

 2003 Prentice Hall, Inc. All rights reserved. 37 Operator Functions As Class Members Vs. As Friend Functions Operator functions –Member functions Use this keyword to implicitly get argument Gets left operand for binary operators (like + ) Leftmost object must be of same class as operator –Non member functions Need parameters for both operands Can have object of different class than operator Must be a friend to access private or protected data Example Overloaded << operator –Left operand of type ostream & Such as cout object in cout << classObject –Similarly, overloaded >> needs istream & –Thus, both must be non-member functions

 2003 Prentice Hall, Inc. All rights reserved. 38 Operator Functions As Class Members Vs. As Friend Functions Commutative operators –May want + to be commutative So both “ a + b ” and “ b + a ” work –Suppose we have two different classes –Overloaded operator can only be member function when its class is on left HugeIntClass + Long int Can be member function –When other way, need a non-member overload function Long int + HugeIntClass

 2003 Prentice Hall, Inc. All rights reserved. 39 Overloading Stream-Insertion and Stream- Extraction Operators > –Already overloaded to process each built-in type –Can also process a user-defined class Example program –Class PhoneNumber Holds a telephone number –Print out formatted number automatically (123)

 2003 Prentice Hall, Inc. All rights reserved. Outline 40 fig08_03.cpp (1 of 3) 1 // Fig. 8.3: fig08_03.cpp 2 // Overloading the stream-insertion and 3 // stream-extraction operators. 4 #include 5 6 using std::cout; 7 using std::cin; 8 using std::endl; 9 using std::ostream; 10 using std::istream; #include using std::setw; // PhoneNumber class definition 17 class PhoneNumber { 18 friend ostream &operator<<( ostream&, const PhoneNumber & ); 19 friend istream &operator>>( istream&, PhoneNumber & ); private: 22 char areaCode[ 4 ]; // 3-digit area code and null 23 char exchange[ 4 ]; // 3-digit exchange and null 24 char line[ 5 ]; // 4-digit line and null }; // end class PhoneNumber Notice function prototypes for overloaded operators >> and << They must be non-member friend functions, since the object of class Phonenumber appears on the right of the operator. cin > object

 2003 Prentice Hall, Inc. All rights reserved. Outline 41 fig08_03.cpp (2 of 3) // overloaded stream-insertion operator; cannot be 29 // a member function if we would like to invoke it with 30 // cout << somePhoneNumber; 31 ostream &operator<<( ostream &output, const PhoneNumber &num ) 32 { 33 output << "(" << num.areaCode << ") " 34 << num.exchange << "-" << num.line; return output; // enables cout << a << b << c; } // end function operator<< // overloaded stream-extraction operator; cannot be 41 // a member function if we would like to invoke it with 42 // cin >> somePhoneNumber; 43 istream &operator>>( istream &input, PhoneNumber &num ) 44 { 45 input.ignore(); // skip ( 46 input >> setw( 4 ) >> num.areaCode; // input area code 47 input.ignore( 2 ); // skip ) and space 48 input >> setw( 4 ) >> num.exchange; // input exchange 49 input.ignore(); // skip dash (-) 50 input >> setw( 5 ) >> num.line; // input line return input; // enables cin >> a >> b >> c; The expression: cout << phone; is interpreted as the function call: operator<<(cout, phone); output is an alias for cout. This allows objects to be cascaded. cout << phone1 << phone2; first calls operator<<(cout, phone1), and returns cout. Next, cout << phone2 executes. Stream manipulator setw restricts number of characters read. setw(4) allows 3 characters to be read, leaving room for the null character.

 2003 Prentice Hall, Inc. All rights reserved. Outline 42 fig08_03.cpp (3 of 3) fig08_03.cpp output (1 of 1) } // end function operator>> int main() 57 { 58 PhoneNumber phone; // create object phone cout << "Enter phone number in the form (123) :\n"; // cin >> phone invokes operator>> by implicitly issuing 63 // the non-member function call operator>>( cin, phone ) 64 cin >> phone; cout << "The phone number entered was: " ; // cout << phone invokes operator<< by implicitly issuing 69 // the non-member function call operator<<( cout, phone ) 70 cout << phone << endl; return 0; } // end main Enter phone number in the form (123) : (800) The phone number entered was: (800)