Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4: Classes (continued) June 14, 2004

Similar presentations


Presentation on theme: "Lecture 4: Classes (continued) June 14, 2004"— Presentation transcript:

1 Lecture 4: Classes (continued) June 14, 2004
IS Program Design and Software Tools Introduction to C++ Programming Lecture 4: Classes (continued) June 14, 2004

2 Using Set and Get Functions
Set functions Perform validity checks before modifying private data Notify if invalid values Indicate with return values void Time::setHour( int h ) { hour = ( h >= 0 && h < 24 ) ? h : 0; } // end function setHour Get functions “Query” functions Control format of data returned int Time::getHour() return hour;

3 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

4 // Fig. 6.21: time4.h // Declaration of class Time. // Member functions defined in time4.cpp 4 // prevent multiple inclusions of header file #ifndef TIME4_H #define TIME4_H 8 class Time { 10 11 public: Time( int = 0, int = 0, int = 0 ); void setTime( int, int, int ); int getHour(); 15 int &badSetHour( int ); // DANGEROUS reference return 17 18 private: int hour; int minute; int second; 22 23 }; // end class Time 24 25 #endif time4.h (1 of 1) Function to demonstrate effects of returning reference to private data member.

5 Return reference to private data member hour.
25 // return hour value 26 int Time::getHour() 27 { return hour; 29 30 } // end function getHour 31 32 // POOR PROGRAMMING PRACTICE: 33 // Returning a reference to a private data member. 34 int &Time::badSetHour( int hh ) 35 { hour = ( hh >= 0 && hh < 24 ) ? hh : 0; 37 return hour; // DANGEROUS reference return 39 40 } // end function badSetHour time4.cpp (2 of 2) Return reference to private data member hour.

6 badSetHour returns reference to private data member hour.
// Fig. 6.23: fig06_23.cpp // Demonstrating a public member function that // returns a reference to a private data member. #include <iostream> 5 using std::cout; using std::endl; 8 // include definition of class Time from time4.h 10 #include "time4.h" 11 12 int main() 13 { Time t; 15 // store in hourRef the reference returned by badSetHour int &hourRef = t.badSetHour( 20 ); 18 cout << "Hour before modification: " << hourRef; 20 // use hourRef to set invalid value in Time object t hourRef = 30; 23 cout << "\nHour after modification: " << t.getHour(); 25 fig06_23.cpp (1 of 2) badSetHour returns reference to private data member hour. Reference allows setting of private data member hour.

7 fig06_23.cpp (2 of 2) fig06_23.cpp output (1 of 1)
// Dangerous: Function call that returns // a reference can be used as an lvalue! t.badSetHour( 12 ) = 74; 29 cout << "\n\n*********************************\n" << "POOR PROGRAMMING PRACTICE!!!!!!!!\n" << "badSetHour as an lvalue, Hour: " << t.getHour() << "\n*********************************" << endl; 35 return 0; 37 38 } // end main Can use function call as lvalue to set invalid value. fig06_23.cpp (2 of 2) fig06_23.cpp output (1 of 1) Hour before modification: 20 Hour after modification: 30 ********************************* POOR PROGRAMMING PRACTICE!!!!!!!! badSetHour as an lvalue, Hour: 74 Returning reference allowed invalid setting of private data member hour.

8 Default Memberwise Assignment
Assigning objects Assignment operator (=) Can assign one object to another of same type Default: member-wise assignment Each right member assigned individually to left member class Date { public: Date( int = 1, int = 1, int = 1990 ); // default constructor void print(); ... }; // end class Date Passing, returning objects Objects passed as function arguments Objects returned from functions Copy constructor

9 const (Constant) Objects and const Member Functions
Principle of least privilege Only allow modification of necessary objects Keyword const Specify object not modifiable Compiler error if attempt to modify const object Example const Time noon( 12, 0, 0 ); Declares const object noon of class Time Initializes to 12

10 const (Constant) Objects and const Member Functions
Member functions for const objects must also be const Cannot modify object Specify const in both prototype and definition Prototype: After parameter list void printUniversal() const; Definition: Before beginning left brace void printUniversal() const { .. } Constructors and destructors Cannot be const Must be able to modify objects

11 const (Constant) Objects and const Member Functions
Member initializer syntax Initializing with member initializer syntax Can be used for All data members Must be used for const data members Data members that are references Constructors and destructors Cannot be const Must be able to modify objects Constructor Initializes objects Destructor Performs termination housekeeping

12 fig07_04.cpp (1 of 3) 1 // Fig. 7.4: fig07_04.cpp
// Using a member initializer to initialize a // constant of a built-in data type. #include <iostream> 5 using std::cout; using std::endl; 8 class Increment { 10 11 public: Increment( int c = 0, int i = 1 ); // default constructor 13 void addIncrement() { count += increment; 17 } // end function addIncrement 19 void print() const; // prints count and increment 21 fig07_04.cpp (1 of 3)

13 Declare increment as const data member. fig07_04.cpp (2 of 3)
22 private: int count; const int increment; // const data member 25 26 }; // end class Increment 27 28 // constructor 29 Increment::Increment( int c, int i ) : count( c ), // initializer for non-const member increment( i ) // required initializer for const member 32 { // empty body 34 35 } // end Increment constructor 36 37 // print count and increment values 38 void Increment::print() const 39 { cout << "count = " << count << ", increment = " << increment << endl; 42 43 } // end function print 44 Declare increment as const data member. fig07_04.cpp (2 of 3) Member initializer list separated from parameter list by colon. Member initializer syntax can be used for non-const data member count. Member initializer syntax must be used for const data member increment. Member initializer consists of data member name (increment) followed by parentheses containing initial value (c).

14 Composition: Objects as Members of Classes
Class has objects of other classes as members Construction of objects Member objects constructed in order declared Not in order of constructor’s member initializer list Constructed before enclosing class objects (host objects)

15 date1.h (1 of 1) 1 // Fig. 7.6: date1.h 2 // Date class definition.
// Member functions defined in date1.cpp #ifndef DATE1_H #define DATE1_H 6 class Date { 8 public: Date( int = 1, int = 1, int = 1900 ); // default constructor void print() const; // print date in month/day/year format ~Date(); // provided to confirm destruction order 13 14 private: int month; // 1-12 (January-December) int day; // 1-31 based on month int year; // any year 18 // utility function to test proper day for month and year int checkDay( int ) const; 21 22 }; // end class Date 23 24 #endif date1.h (1 of 1)

16 date1.cpp (1 of 3) 1 // Fig. 7.7: date1.cpp
// Member-function definitions for class Date. #include <iostream> 4 using std::cout; using std::endl; 7 // include Date class definition from date1.h #include "date1.h" 10 11 // constructor confirms proper value for month; calls 12 // utility function checkDay to confirm proper value for day 13 Date::Date( int mn, int dy, int yr ) 14 { if ( mn > 0 && mn <= 12 ) // validate the month month = mn; 17 else { // invalid month set to 1 month = 1; cout << "Month " << mn << " invalid. Set to month 1.\n"; } 22 year = yr; // should validate yr day = checkDay( dy ); // validate the day 25 date1.cpp (1 of 3)

17 // Fig. 7.8: employee1.h // Employee class definition. // Member functions defined in employee1.cpp. #ifndef EMPLOYEE1_H #define EMPLOYEE1_H 6 // include Date class definition from date1.h #include "date1.h" 9 10 class Employee { 11 12 public: Employee( const char *, const char *, const Date &, const Date & ); 15 void print() const; ~Employee(); // provided to confirm destruction order 18 19 private: char firstName[ 25 ]; char lastName[ 25 ]; const Date birthDate; // composition: member object const Date hireDate; // composition: member object 24 25 }; // end class Employee employee1.h (1 of 2) Using composition; Employee object contains Date objects as data members.

18 employee1.h (2 of 2) employee1.cpp (1 of 3)
26 27 #endif employee1.h (2 of 2) employee1.cpp (1 of 3) // Fig. 7.9: employee1.cpp // Member-function definitions for class Employee. #include <iostream> 4 using std::cout; using std::endl; 7 #include <cstring> // strcpy and strlen prototypes 9 10 #include "employee1.h" // Employee class definition 11 #include "date1.h" // Date class definition 12

19 Output to show timing of constructors.
13 // constructor uses member initializer list to pass initializer 14 // values to constructors of member objects birthDate and 15 // hireDate [Note: This invokes the so-called "default copy 16 // constructor" which the C++ compiler provides implicitly.] 17 Employee::Employee( const char *first, const char *last, const Date &dateOfBirth, const Date &dateOfHire ) : birthDate( dateOfBirth ), // initialize birthDate hireDate( dateOfHire ) // initialize hireDate 21 { // copy first into firstName and be sure that it fits int length = strlen( first ); length = ( length < 25 ? length : 24 ); strncpy( firstName, first, length ); firstName[ length ] = '\0'; 27 // copy last into lastName and be sure that it fits length = strlen( last ); length = ( length < 25 ? length : 24 ); strncpy( lastName, last, length ); lastName[ length ] = '\0'; 33 // output Employee object to show when constructor is called cout << "Employee object constructor: " << firstName << ' ' << lastName << endl; 37 employee1.cpp (2 of 3) Member initializer syntax to initialize Date data members birthDate and hireDate; compiler uses default copy constructor. Output to show timing of constructors.

20 Output to show timing of destructors.
38 } // end Employee constructor 39 40 // print Employee object 41 void Employee::print() const 42 { cout << lastName << ", " << firstName << "\nHired: "; hireDate.print(); cout << " Birth date: "; birthDate.print(); cout << endl; 48 49 } // end function print 50 51 // output Employee object to show when its destructor is called 52 Employee::~Employee() 53 { cout << "Employee object destructor: " << lastName << ", " << firstName << endl; 56 57 } // end destructor ~Employee employee1.cpp (3 of 3) Output to show timing of destructors.

21 Create Date objects to pass to Employee constructor.
// Fig. 7.10: fig07_10.cpp // Demonstrating composition--an object with member objects. #include <iostream> 4 using std::cout; using std::endl; 7 #include "employee1.h" // Employee class definition 9 10 int main() 11 { Date birth( 7, 24, 1949 ); Date hire( 3, 12, 1988 ); Employee manager( "Bob", "Jones", birth, hire ); 15 cout << '\n'; manager.print(); 18 cout << "\nTest Date constructor with invalid values:\n"; Date lastDayOff( 14, 35, 1994 ); // invalid month and day cout << endl; 22 return 0; 24 25 } // end main fig07_10.cpp (1 of 1) Create Date objects to pass to Employee constructor.

22 Destructor for Employee’s member object hireDate.
Date object constructor for date 7/24/1949 Date object constructor for date 3/12/1988 Employee object constructor: Bob Jones Jones, Bob Hired: 3/12/1988 Birth date: 7/24/1949 Test Date constructor with invalid values: Month 14 invalid. Set to month 1. Day 35 invalid. Set to day 1. Date object constructor for date 1/1/1994 Date object destructor for date 1/1/1994 Employee object destructor: Jones, Bob Date object destructor for date 3/12/1988 Date object destructor for date 7/24/1949 Note two additional Date objects constructed; no output since default copy constructor used. fig07_10.cpp output (1 of 1) Destructor for host object manager runs before destructors for member objects hireDate and birthDate. Destructor for Employee’s member object hireDate. Destructor for Employee‘s member object birthDate. Destructor for Date object hire. Destructor for Date object birth.

23 friend Functions and friend Classes
Defined outside class’s scope Right to access non-public members Declaring friends Function Precede function prototype with keyword friend Want to make all member functions of class ClassTwo as friends of class ClassOne Place declaration of form friend class ClassTwo; in ClassOne definition

24 friend Functions and friend Classes
Properties of friendship Friendship granted, not taken Class B friend of class A Class A must explicitly declare class B friend Not symmetric Class A not necessarily friend of class B Not transitive Class A friend of class B Class B friend of class C Class A not necessarily friend of Class C

25 Precede function prototype with keyword friend.
// Fig. 7.11: fig07_11.cpp // Friends can access private members of a class. #include <iostream> 4 using std::cout; using std::endl; 7 // Count class definition class Count { friend void setX( Count &, int ); // friend declaration 11 12 public: 13 // constructor Count() : x( 0 ) // initialize x to 0 { // empty body 19 } // end Count constructor 21 fig07_11.cpp (1 of 3) Precede function prototype with keyword friend.

26 Pass Count object since C-style, standalone function.
// output x void print() const { cout << x << endl; 26 } // end function print 28 29 private: int x; // data member 31 32 }; // end class Count 33 34 // function setX can modify private data of Count 35 // because setX is declared as a friend of Count 36 void setX( Count &c, int val ) 37 { c.x = val; // legal: setX is a friend of Count 39 40 } // end function setX 41 fig07_11.cpp (2 of 3) Pass Count object since C-style, standalone function. Since setX friend of Count, can access and modify private data member x.

27 fig07_11.cpp (3 of 3) fig07_11.cpp output (1 of 1)
42 int main() 43 { Count counter; // create Count object 45 cout << "counter.x after instantiation: "; counter.print(); 48 setX( counter, 8 ); // set x with a friend 50 cout << "counter.x after call to setX friend function: "; counter.print(); 53 return 0; 55 56 } // end main fig07_11.cpp (3 of 3) fig07_11.cpp output (1 of 1) Use friend function to access and modify private data member x. counter.x after instantiation: 0 counter.x after call to setX friend function: 8

28 Using the this Pointer this pointer
Allows object to access own address Not part of object itself Implicit argument to non-static member function call Implicitly reference member data and functions Type of this pointer depends on Type of object Whether member function is const In non-const member function of Employee this has type Employee * const Constant pointer to non-constant Employee object In const member function of Employee this has type const Employee * const Constant pointer to constant Employee object

29 fig07_13.cpp (1 of 3) 1 // Fig. 7.13: fig07_13.cpp
// Using the this pointer to refer to object members. #include <iostream> 4 using std::cout; using std::endl; 7 class Test { 9 10 public: Test( int = 0 ); // default constructor void print() const; 13 14 private: int x; 16 17 }; // end class Test 18 19 // constructor 20 Test::Test( int value ) : x( value ) // initialize x to value 22 { // empty body 24 25 } // end Test constructor fig07_13.cpp (1 of 3)

30 Implicitly use this pointer; only specify name of data member (x).
26 27 // print x using implicit and explicit this pointers; 28 // parentheses around *this required 29 void Test::print() const 30 { // implicitly use this pointer to access member x cout << " x = " << x; 33 // explicitly use this pointer to access member x cout << "\n this->x = " << this->x; 36 // explicitly use dereferenced this pointer and // the dot operator to access member x cout << "\n(*this).x = " << ( *this ).x << endl; 40 41 } // end function print 42 43 int main() 44 { Test testObject( 12 ); 46 testObject.print(); 48 return 0; 50 Implicitly use this pointer; only specify name of data member (x). fig07_13.cpp (2 of 3) Explicitly use this pointer with arrow operator. Explicitly use this pointer; dereference this pointer first, then use dot operator.

31 fig07_13.cpp (3 of 3) fig07_13.cpp output (1 of 1)
51 } // end main x = 12 this->x = 12 (*this).x = 12 fig07_13.cpp (3 of 3) fig07_13.cpp output (1 of 1)

32 Cascaded member function calls
Using the this Pointer Cascaded member function calls Multiple functions invoked in same statement Function returns reference pointer to same object { return *this; } Other functions operate on that pointer Functions that do not return references must be called last

33 // Fig. 7.14: time6.h // Cascading member function calls. 3 // Time class definition. // Member functions defined in time6.cpp. #ifndef TIME6_H #define TIME6_H 8 class Time { 10 11 public: Time( int = 0, int = 0, int = 0 ); // default constructor 13 // set functions Time &setTime( int, int, int ); // set hour, minute, second Time &setHour( int ); // set hour Time &setMinute( int ); // set minute Time &setSecond( int ); // set second 19 // get functions (normally declared const) int getHour() const; // return hour int getMinute() const; // return minute int getSecond() const; // return second 24 time6.h (1 of 2) Set functions return reference to Time object to enable cascaded member function calls.

34 time6.h (2 of 2) 25 // print functions (normally declared const)
void printUniversal() const; // print universal time void printStandard() const; // print standard time 28 29 private: int hour; // (24-hour clock format) int minute; // int second; // 33 34 }; // end class Time 35 36 #endif time6.h (2 of 2)

35 time6.cpp (1 of 5) 1 // Fig. 7.15: time6.cpp
// Member-function definitions for Time class. #include <iostream> 4 using std::cout; 6 #include <iomanip> 8 using std::setfill; 10 using std::setw; 11 12 #include "time6.h" // Time class definition 13 14 // constructor function to initialize private data; 15 // calls member function setTime to set variables; 16 // default values are 0 (see class definition) 17 Time::Time( int hr, int min, int sec ) 18 { setTime( hr, min, sec ); 20 21 } // end Time constructor 22 time6.cpp (1 of 5)

36 Return *this as reference to enable cascaded member function calls.
23 // set values of hour, minute, and second 24 Time &Time::setTime( int h, int m, int s ) 25 { setHour( h ); setMinute( m ); setSecond( s ); 29 return *this; // enables cascading 31 32 } // end function setTime 33 34 // set hour value 35 Time &Time::setHour( int h ) 36 { hour = ( h >= 0 && h < 24 ) ? h : 0; 38 return *this; // enables cascading 40 41 } // end function setHour 42 time6.cpp (2 of 5) Return *this as reference to enable cascaded member function calls. Return *this as reference to enable cascaded member function calls.

37 Return *this as reference to enable cascaded member function calls.
43 // set minute value 44 Time &Time::setMinute( int m ) 45 { minute = ( m >= 0 && m < 60 ) ? m : 0; 47 return *this; // enables cascading 49 50 } // end function setMinute 51 52 // set second value 53 Time &Time::setSecond( int s ) 54 { second = ( s >= 0 && s < 60 ) ? s : 0; 56 return *this; // enables cascading 58 59 } // end function setSecond 60 61 // get hour value 62 int Time::getHour() const 63 { return hour; 65 66 } // end function getHour 67 Return *this as reference to enable cascaded member function calls. time6.cpp (3 of 5) Return *this as reference to enable cascaded member function calls.

38 time6.cpp (4 of 5) 68 // get minute value
69 int Time::getMinute() const 70 { return minute; 72 73 } // end function getMinute 74 75 // get second value 76 int Time::getSecond() const 77 { return second; 79 80 } // end function getSecond 81 82 // print Time in universal format 83 void Time::printUniversal() const 84 { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; 88 89 } // end function printUniversal 90 time6.cpp (4 of 5)

39 time6.cpp (5 of 5) 91 // print Time in standard format
92 void Time::printStandard() const 93 { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); 98 99 } // end function printStandard time6.cpp (5 of 5)

40 // Fig. 7.16: fig07_16.cpp // Cascading member function calls with the this pointer. #include <iostream> 4 using std::cout; using std::endl; 7 #include "time6.h" // Time class definition 9 10 int main() 11 { Time t; 13 // cascaded function calls t.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); 16 // output time in universal and standard formats cout << "Universal time: "; t.printUniversal(); 20 cout << "\nStandard time: "; t.printStandard(); 23 cout << "\n\nNew standard time: "; 25 fig07_16.cpp (1 of 2) Cascade member function calls; recall dot operator associates from left to right.

41 fig07_16.cpp (2 of 2) fig07_16.cpp output (1 of 1)
// cascaded function calls t.setTime( 20, 20, 20 ).printStandard(); 28 cout << endl; 30 return 0; 32 33 } // end main Function call to printStandard must appear last; printStandard does not return reference to t. fig07_16.cpp (2 of 2) fig07_16.cpp output (1 of 1) Universal time: 18:30:22 Standard time: 6:30:22 PM New standard time: 8:20:20 PM

42 Dynamic Memory Management with Operators new and delete
Control allocation and deallocation of memory Operators new and delete Include standard header <new> 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 ];

43 Dynamic Memory Management with Operators new and 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

44 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

45 Accessing static class variables
static Class Members Accessing static class variables Accessible through any object of class public static variables Can also be accessed using binary scope resolution operator(::) Employee::count private static variables When no class member objects exist Can only be accessed via public static member function To call public static member function combine class name, binary scope resolution operator (::) and function name Employee::getCount()

46 static member functions
static Class Members static member functions Cannot access non-static data or functions No this pointer for static functions static data members and static member functions exist independent of objects

47 static data member is class-wide data.
// Fig. 7.17: employee2.h // Employee class definition. #ifndef EMPLOYEE2_H #define EMPLOYEE2_H 5 class Employee { 7 public: Employee( const char *, const char * ); // constructor ~Employee(); // destructor const char *getFirstName() const; // return first name const char *getLastName() const; // return last name 13 // static member function static int getCount(); // return # objects instantiated 16 17 private: char *firstName; char *lastName; 20 // static data member static int count; // number of objects instantiated 23 24 }; // end class Employee 25 employee2.h (1 of 2) static member function can only access static data members and member functions. static data member is class-wide data.

48 employee2.h (2 of 2) employee2.cpp (1 of 3)
26 #endif // Fig. 7.18: employee2.cpp // Member-function definitions for class Employee. #include <iostream> 4 using std::cout; using std::endl; 7 #include <new> // C++ standard new operator #include <cstring> // strcpy and strlen prototypes 10 11 #include "employee2.h" // Employee class definition 12 13 // define and initialize static data member 14 int Employee::count = 0; 15 16 // define static member function that returns number of 17 // Employee objects instantiated 18 int Employee::getCount() 19 { return count; 21 22 } // end static function getCount employee2.h (2 of 2) employee2.cpp (1 of 3) Initialize static data member exactly once at file scope. static member function accesses static data member count.

49 new operator dynamically allocates space.
23 24 // 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 { firstName = new char[ strlen( first ) + 1 ]; strcpy( firstName, first ); 31 lastName = new char[ strlen( last ) + 1 ]; strcpy( lastName, last ); 34 count; // increment static count of employees 36 cout << "Employee constructor for " << firstName << ' ' << lastName << " called." << endl; 39 40 } // end Employee constructor 41 42 // destructor deallocates dynamically allocated memory 43 Employee::~Employee() 44 { cout << "~Employee() called for " << firstName << ' ' << lastName << endl; 47 employee2.cpp (2 of 3) new operator dynamically allocates space. Use static data member to store total count of employees.

50 Operator delete deallocates memory. employee2.cpp (3 of 3)
delete [] firstName; // recapture memory delete [] lastName; // recapture memory 50 count; // decrement static count of employees 52 53 } // end destructor ~Employee 54 55 // return first name of employee 56 const char *Employee::getFirstName() const 57 { // const before return type prevents client from modifying // private data; client should copy returned string before // destructor deletes storage to prevent undefined pointer return firstName; 62 63 } // end function getFirstName 64 65 // return last name of employee 66 const char *Employee::getLastName() const 67 { // const before return type prevents client from modifying // private data; client should copy returned string before // destructor deletes storage to prevent undefined pointer return lastName; 72 73 } // end function getLastName Operator delete deallocates memory. employee2.cpp (3 of 3) Use static data member to store total count of employees.

51 new operator dynamically allocates space.
// Fig. 7.19: fig07_19.cpp // Driver to test class Employee. #include <iostream> 4 using std::cout; using std::endl; 7 #include <new> // C++ standard new operator 9 10 #include "employee2.h" // Employee class definition 11 12 int main() 13 { cout << "Number of employees before instantiation is " << Employee::getCount() << endl; // use class name 16 Employee *e1Ptr = new Employee( "Susan", "Baker" ); Employee *e2Ptr = new Employee( "Robert", "Jones" ); 19 cout << "Number of employees after instantiation is " << e1Ptr->getCount(); 22 fig07_19.cpp (1 of 2) new operator dynamically allocates space. static member function can be invoked on any object of class.

52 Operator delete deallocates memory.
cout << "\n\nEmployee 1: " << e1Ptr->getFirstName() << " " << e1Ptr->getLastName() << "\nEmployee 2: " << e2Ptr->getFirstName() << " " << e2Ptr->getLastName() << "\n\n"; 29 delete e1Ptr; // recapture memory e1Ptr = 0; // disconnect pointer from free-store space delete e2Ptr; // recapture memory e2Ptr = 0; // disconnect pointer from free-store space 34 cout << "Number of employees after deletion is " << Employee::getCount() << endl; 37 return 0; 39 40 } // end main fig07_19.cpp (2 of 2) Operator delete deallocates memory. static member function invoked using binary scope resolution operator (no existing class objects).

53 Number of employees before instantiation is 0
Employee constructor for Susan Baker called. Employee constructor for Robert Jones called. Number of employees after instantiation is 2 Employee 1: Susan Baker Employee 2: Robert Jones ~Employee() called for Susan Baker ~Employee() called for Robert Jones Number of employees after deletion is 0 fig07_19.cpp output (1 of 1)

54 Data Abstraction and Information Hiding
Classes hide implementation details from clients Example: stack data structure Data elements added (pushed) onto top Data elements removed (popped) from top Last-in, first-out (LIFO) data structure Client only wants LIFO data structure Does not care how stack implemented Data abstraction Describe functionality of class independent of implementation

55 Data Abstraction and Information Hiding
Abstract data types (ADTs) Approximations/models of real-world concepts and behaviors int, float are models for a numbers Data representation Operations allowed on those data C++ extensible Standard data types cannot be changed, but new data types can be created

56 Forward class declaration
Proxy Classes Proxy class Hide implementation details of another class Knows only public interface of class being hidden Enables clients to use class’s services without giving access to class’s implementation Forward class declaration Used when class definition only uses pointer to another class Prevents need for including header file Declares class before referencing Format: class ClassToLoad;

57 public member function.
// Fig. 7.20: implementation.h // Header file for class Implementation 3 class Implementation { 5 public: 7 // constructor Implementation( int v ) : value( v ) // initialize value with v { // empty body 13 } // end Implementation constructor 15 // set value to v void setValue( int v ) { value = v; // should validate v 20 } // end function setValue 22 implementation.h (1 of 2) public member function.

58 public member function. implementation.h (2 of 2)
// return value int getValue() const { return value; 27 } // end function getValue 29 30 private: int value; 32 33 }; // end class Implementation public member function. implementation.h (2 of 2)

59 Pointer to Implementation object requires forward class declaration.
// Fig. 7.21: interface.h // Header file for interface.cpp 3 class Implementation; // forward class declaration 5 class Interface { 7 public: Interface( int ); void setValue( int ); // same public interface as int getValue() const; // class Implementation ~Interface(); 13 14 private: 15 // requires previous forward declaration (line 4) Implementation *ptr; 18 19 }; // end class Interface interface.h (1 of 1) Pointer to Implementation object requires forward class declaration. Provide same public interface as class Implementation; recall setValue and getValue only public member functions.

60 Maintain pointer to underlying Implementation object.
// Fig. 7.22: interface.cpp // Definition of class Interface #include "interface.h" // Interface class definition #include "implementation.h" // Implementation class definition 5 // constructor Interface::Interface( int v ) : ptr ( new Implementation( v ) ) // initialize ptr { // empty body 11 12 } // end Interface constructor 13 14 // call Implementation's setValue function 15 void Interface::setValue( int v ) 16 { ptr->setValue( v ); 18 19 } // end function setValue 20 Maintain pointer to underlying Implementation object. interface.cpp (1 of 2) Proxy class Interface includes header file for class Implementation. Invoke corresponding function on underlying Implementation object.

61 Invoke corresponding function on underlying Implementation object.
21 // call Implementation's getValue function 22 int Interface::getValue() const 23 { return ptr->getValue(); 25 26 } // end function getValue 27 28 // destructor 29 Interface::~Interface() 30 { delete ptr; 32 33 } // end destructor ~Interface Invoke corresponding function on underlying Implementation object. interface.cpp (2 of 2) Deallocate underlying Implementation object.

62 fig07_23.cpp (1 of 1) fig07_23.cpp output (1 of 1)
// Fig. 7.23: fig07_23.cpp // Hiding a class’s private data with a proxy class. #include <iostream> 4 using std::cout; using std::endl; 7 #include "interface.h" // Interface class definition 9 10 int main() 11 { Interface i( 5 ); 13 cout << "Interface contains: " << i.getValue() << " before setValue" << endl; 16 i.setValue( 10 ); 18 cout << "Interface contains: " << i.getValue() << " after setValue" << endl; 21 return 0; 23 24 } // end main fig07_23.cpp (1 of 1) fig07_23.cpp output (1 of 1) Only include proxy class header file. Create object of proxy class Interface; note no mention of Implementation class. Invoke member functions via proxy class object. Interface contains: 5 before setValue Interface contains: 10 after setValue


Download ppt "Lecture 4: Classes (continued) June 14, 2004"

Similar presentations


Ads by Google