Chapter 1 - Introduction to Computers and C++ Programming

Chapter 1 - Introduction to Computers and C++ Programming

1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 5: Classes (continued) Feb 1, 2005 2003 Prentice Hall, Inc. All rights reserved. 2 friend Functions and friend Classes friend function Defined outside classs 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 2003 Prentice Hall, Inc. All rights reserved. 3 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 B friend of class A 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

2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 7.11: fig07_11.cpp // Friends can access private members of a class. #include using std::cout; using std::endl; Precede function prototype with keyword friend. Outline fig07_11.cpp (1 of 3) // Count class definition class Count { friend void setX( Count &, int ); // friend declaration public: // constructor Count() : x( 0 ) // initialize x to 0 { // empty body } // end Count constructor

2003 Prentice Hall, Inc. All rights reserved. 4 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 // output x void print() const { cout << x << endl; } // end function print private: int x; Outline fig07_11.cpp (2 of 3) // data member }; // end class Count Pass Count object since Cstyle, data standalone function. // function setX can modify private

of Count Since setX ofCount // because setX is declared as a friend friend of Count, access and void setX( Count &c, int val can ) modify private data { c.x = val; // legal: setXx. is a friend of Count member } // end function setX 2003 Prentice Hall, Inc. All rights reserved. 5 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 int main() { Count counter; Outline // create Count object

Use friend function to cout << "counter.x after instantiation: "; access and modify private counter.print(); data member x. setX( counter, 8 ); // set x with a friend fig07_11.cpp (3 of 3) fig07_11.cpp output (1 of 1) cout << "counter.x after call to setX friend function: "; counter.print(); return 0; } // end main counter.x after instantiation: 0 counter.x after call to setX friend function: 8 2003 Prentice Hall, Inc. All rights reserved. 6 7 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 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 7.13: fig07_13.cpp // Using the this pointer to refer to object members. #include using std::cout; using std::endl; Outline fig07_13.cpp (1 of 3) class Test { public: Test( int = 0 ); // default constructor void print() const; private: int x; }; // end class Test

// constructor Test::Test( int value ) : x( value ) // initialize x to value { // empty body } // end Test constructor 2003 Prentice Hall, Inc. All rights reserved. 8 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 Outline // print x using implicit and explicit this pointers; // parentheses around *this required Implicitly use this pointer; void Test::print() const only specify name of data fig07_13.cpp {

(2 of 3) member (x). // implicitly use this pointer to access member x Explicitly use this pointer cout << " x = " << x; with arrow operator. // explicitly use this pointer to access member x cout << "\n this->x = " << this->x; // explicitly use dereferenced this pointer and // the dot operator to access member x cout << "\n(*this).x = " << ( *this ).x << endl; Explicitly use this pointer; dereference this pointer first, then use dot operator. } // end function print int main() { Test testObject( 12 ); testObject.print(); return 0; } // end main x = 12 this->x = 12 (*this).x = 12 2003 Prentice Hall, Inc. All rights reserved. 9 10 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 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 7.14: time6.h // Cascading member function calls. Outline // Time class definition. // Member functions defined in time6.cpp. #ifndef TIME6_H #define TIME6_H time6.h (1 of 2) class Time { public: Time( int = 0, int = 0, int = 0 ); // set functions Time &setTime( int, int, Time &setHour( int );

Time &setMinute( int ); Time &setSecond( int ); int ); // set // set // set Set functions return reference // default constructor to Time object to enable cascaded member function calls. // set hour, minute, second hour minute second // get functions (normally declared const) int getHour() const; // return hour int getMinute() const; // return minute int getSecond() const; // return second 2003 Prentice Hall, Inc. All rights reserved. 11 25 26 27 28 29 30 31 32 33 34 35

36 // print functions (normally declared const) void printUniversal() const; // print universal time void printStandard() const; // print standard time private: int hour; int minute; int second; Outline time6.h (2 of 2) // 0 - 23 (24-hour clock format) // 0 - 59 // 0 - 59 }; // end class Time #endif 2003 Prentice Hall, Inc. All rights reserved. 12 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

22 // Fig. 7.15: time6.cpp // Member-function definitions for Time class. #include Outline time6.cpp (1 of 5) using std::cout; #include using std::setfill; using std::setw; #include "time6.h" // Time class definition // constructor function to initialize private data; // calls member function setTime to set variables; // default values are 0 (see class definition) Time::Time( int hr, int min, int sec ) { setTime( hr, min, sec ); } // end Time constructor 2003 Prentice Hall, Inc. All rights reserved. 13 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

40 41 42 // set values of hour, minute, and second Time &Time::setTime( int h, int m, int s ) { setHour( h ); setMinute( m ); Return *this as reference setSecond( s ); enable cascaded member return *this; Outline to time6.cpp (2 of 5) function calls. // enables cascading } // end function setTime // set hour value Time &Time::setHour( int h ) { Return *this as reference hour = ( h >= 0 && h < 24 ) ? henable : 0; cascaded member return *this; to function calls. // enables cascading } // end function setHour 2003 Prentice Hall, Inc. All rights reserved. 14 43 44

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

? s : 0; cascaded member return *this; to function calls. // enables cascading } // end function setSecond // get hour value int Time::getHour() const { return hour; } // end function getHour 2003 Prentice Hall, Inc. All rights reserved. 15 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 // get minute value

int Time::getMinute() const { return minute; Outline time6.cpp (4 of 5) } // end function getMinute // get second value int Time::getSecond() const { return second; } // end function getSecond // print Time in universal format void Time::printUniversal() const { cout << setfill( '0' ) << setw( 2 ) << hour << ":" << setw( 2 ) << minute << ":" << setw( 2 ) << second; } // end function printUniversal 2003 Prentice Hall, Inc. All rights reserved. 16 91 92 93 94 95 96 97 98 99 // print Time in standard format void Time::printStandard() const { cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 ) << ":" << setfill( '0' ) << setw( 2 ) << minute << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" ); Outline time6.cpp (5 of 5)

} // end function printStandard 2003 Prentice Hall, Inc. All rights reserved. 17 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 7.16: fig07_16.cpp // Cascading member function calls with the this pointer. #include fig07_16.cpp (1 of 2) using std::cout; using std::endl; #include "time6.h" Outline // Time class definition

int main() { Time t; Cascade member function calls; recall dot operator associates from left to right. // cascaded function calls t.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); // output time in universal and standard formats cout << "Universal time: "; t.printUniversal(); cout << "\nStandard time: "; t.printStandard(); cout << "\n\nNew standard time: "; 2003 Prentice Hall, Inc. All rights reserved. 18 26 27 28 29 30 31 32 33 // cascaded function calls t.setTime( 20, 20, 20 ).printStandard(); cout << endl; return 0; } // end main Outline Function call to fig07_16.cpp printStandard must (2 of 2) appear last; printStandard does not fig07_16.cpp return reference to t. output (1 of 1)

Universal time: 18:30:22 Standard time: 6:30:22 PM New standard time: 8:20:20 PM 2003 Prentice Hall, Inc. All rights reserved. 19 Dynamic Memory Management with Operators new and delete Dynamic memory management Control allocation and deallocation of memory Operators new and delete new Include standard header 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( 3.14159 ); Time *timePtr = new Time( 12, 0, 0 ); Allocating arrays int *gradesArray = new int[ 10 ]; 2003 Prentice Hall, Inc. All rights reserved. 20 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. 21 22 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. 23 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. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Fig. 7.17: employee2.h // Employee class definition. #ifndef EMPLOYEE2_H #define EMPLOYEE2_H Outline employee2.h (1 of 2) class Employee { public: Employee( const char *, const char ~Employee();

const char *getFirstName() const; const char *getLastName() const; * ); // constructor // destructor // return first name static member // return last name // static member function static int getCount(); // return # private: char *firstName; char *lastName; 24 function can only access static data members and member objects instantiated functions. static data member is class-wide data. // static data member static int count; // number of objects instantiated }; // end class Employee 2003 Prentice Hall, Inc. All rights reserved. 26 #endif 1 2 3 4 5 6

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 // Fig. 7.18: employee2.cpp // Member-function definitions for class Employee. #include Outline using std::cout; using std::endl; #include #include // C++ standard new operator // strcpy and strlen prototypes #include "employee2.h" Initialize static // Employee class definition // define and initialize static data int Employee::count = 0; 25 employee2.h (2 of 2) employee2.cpp (1 of 3) data member exactly once at file

scope. member static member function data // define static member function that returns number of accesses static // Employee objects instantiated member count. int Employee::getCount() { return count; } // end static function getCount 2003 Prentice Hall, Inc. All rights reserved. 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 Outline // constructor dynamically allocates space for // first and last name and uses strcpy to copy

// first and last names into the object employee2.cpp Employee::Employee( const char *first, const char *last ) new operator dynamically (2 of 3) { allocates space. firstName = new char[ strlen( first ) + 1 ]; strcpy( firstName, first ); Use static lastName = new char[ strlen( last ) + data 1 ];member strcpy( lastName, last );store total count of to employees. ++count; // increment static count of employees cout << "Employee constructor for " << firstName << ' ' << lastName << " called." << endl; } // end Employee constructor // destructor deallocates dynamically allocated memory Employee::~Employee() { cout << "~Employee() called for " << firstName << ' ' << lastName << endl; 2003 Prentice Hall, Inc. All rights reserved. 26 48 49 50 51 52 53 54 55 56

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 delete [] firstName; delete [] lastName; --count; // recapture memory // recapture memory // decrement static count of employees Operator deletetodeallocates data member store totalmemory. count of Use static } // end destructor ~Employee Outline employee2.cpp (3 of 3) // return first name of employee employees. const char *Employee::getFirstName() const { // 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; } // end function getFirstName // return last name of employee const char *Employee::getLastName() const { // 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; } // end function getLastName 2003 Prentice Hall, Inc. All rights reserved. 27 28 Data Abstraction and Information Hiding 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 2003 Prentice Hall, Inc. All rights reserved. 29 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 2003 Prentice Hall, Inc. All rights reserved. 30 Proxy Classes Proxy class Hide implementation details of another class Knows only public interface of class being hidden Enables clients to use classs services without giving access to classs 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; 2003 Prentice Hall, Inc. All rights reserved. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 // Fig. 7.20: implementation.h // Header file for class Implementation Outline class Implementation { implementation.h (1 of 2) public: // constructor Implementation( int v ) : value( v ) // initialize value with v { // empty body } // end Implementation constructor // set value to v void setValue( int v ) { value = v; // should validate v } // end function setValue public member function. 23 // return value 24 int getValue() const 25 { 26 return value; 27 28 } // end function getValue 29 30 private: 31

int value; 32 2003 Prentice Hall, Inc. 33 }; // end class Implementation All rights reserved. 31 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Fig. 7.21: interface.h // Header file for interface.cpp class Implementation; // forward class declaration class Interface { public: Interface( int ); void setValue( int ); int getValue() const; ~Interface(); Outline // // interface.h (1 of 1)

Provide same public interface as class Implementation; recall setValue same public interface as and getValue only public member class Implementation functions. private: // requires previous forward Implementation *ptr; Pointer to Implementation object declaration (line 4) requires forward class declaration. }; // end class Interface 2003 Prentice Hall, Inc. All rights reserved. 32 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

16 17 18 19 20 // Fig. 7.22: interface.cpp // Definition of class Interface #include "interface.h" // Interface class definition #include "implementation.h" // Implementation class definition Maintain pointer to underlying // constructor Proxy class Interface object. Interface::Interface( int v Implementation ) header file for class : ptr ( new Implementation( v ) ) //includes initialize ptr { Implementation. Outline interface.cpp (1 of 2) // empty body } // end Interface constructor // call Implementation's setValue function Invoke corresponding void Interface::setValue( int v ) function on underlying { Implementation object. ptr->setValue( v ); } // end function setValue 2003 Prentice Hall, Inc. All rights reserved. 33

21 22 23 24 25 26 27 28 29 30 31 32 33 // call Implementation's getValue function int Interface::getValue() const { return ptr->getValue(); Invoke corresponding function on underlying Implementation object. } // end function getValue // destructor Interface::~Interface() { delete ptr; Outline interface.cpp (2 of 2) Deallocate underlying Implementation object. } // end destructor ~Interface 2003 Prentice Hall, Inc. All rights reserved. 34 1 2 3

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 7.23: fig07_23.cpp // Hiding a classs private data with a proxy class. #include Only include proxy class header file. using std::cout; using std::endl; #include "interface.h" Outline // Interface class definition int main() { Interface i( 5 ); Create object of proxy class Interface; note no mention of Implementation class. cout << "Interface contains: " << i.getValue()

<< " before setValue" << endl; i.setValue( 10 ); fig07_23.cpp (1 of 1) fig07_23.cpp output (1 of 1) Invoke member functions via proxy class object. cout << "Interface contains: " << i.getValue() << " after setValue" << endl; return 0; } // end main Interface contains: 5 before setValue Interface contains: 10 after setValue 2003 Prentice Hall, Inc. All rights reserved. 35

Recently Viewed Presentations

  • 13 Aggregate Planning McGraw-Hill/Irwin Copyright  2007 by The

    13 Aggregate Planning McGraw-Hill/Irwin Copyright 2007 by The

    Chase demand strategy: Matching capacity to demand; the planned output for a period is set at the expected demand for that period. Chase Approach Advantages Investment in inventory is low Labor utilization in high Disadvantages The cost of adjusting output...
  • Deeper Christian Life Ministry The Netherlands Welcome to

    Deeper Christian Life Ministry The Netherlands Welcome to

    SEARCH THE SCRIPTURES. 07-04-2019. ... Be exalted oh Lord our God Wees verheven O Heermijn God. Hosanna in the highest. Hosanna in de hoge. Be Thou exalted. Be Thou exalted oh God Verhef U boven. Above the heavens de hemel...
  • IAEA SAFETY STANDARDS History, Status, Structure, Contents by

    IAEA SAFETY STANDARDS History, Status, Structure, Contents by

    SSG-2 Deterministic Safety Analysis for Nuclear Power Plants (2009) NS-G-2.15 Severe Accident Management Programmes for Nuclear Power Plants (2009) SSG-15 Storage of Spent Fuel (in publication) GS-G-2.1 Arrangements for Preparedness for a Nuclear or Radiological Emergency (2007)
  • In Mrs Tilscher&#x27;s Class - WordPress.com

    In Mrs Tilscher's Class - WordPress.com

    "In Mrs Tilscher's class/You could travel up the Blue Nile." Word choice - shows how she can inspire the pupils to learn and imagine that they are elsewhere other than the classroom. Creates a sense of mystery and wonder surrounding...
  • In the Name of God

    In the Name of God

    The diffuse carcinomas :younger patients, develop throughout the stomach (including the cardia), result in a loss of distensibilityof the gastric wall (so-called linitis plastica, or "leather bottle" appearance), and carry a poorer prognosis
  • Achieving Noble Gas Electron Configuration

    Achieving Noble Gas Electron Configuration

    Achieving Noble Gas Electron Configuration In this powerpoint, electron orbital filling will be reviewed. Atoms lose electrons (OIL, oxidation) or gain electrons (RIG, reduction) to achieve noble gas electron configuration Recognize the appearance of Bohr's Model after an atom lose...
  • Case Study 10 - University of Pittsburgh

    Case Study 10 - University of Pittsburgh

    Case Study 10 Harry Kellermier, M.D. The patient is a 27-year-old female with a history of complex partial seizures starting at age 16. A typical episode lasts less than one minute and consists of her staring blankly ahead and occasionally...
  • Apresentação do PowerPoint

    Apresentação do PowerPoint

    Outros aspetos: é normal a troca de cartões de visita no início das reuniões (em almoços de negócios são trocados no final da refeição). Os peruanos apreciam apresentações powerpoint e têm normalmente os meios necessários para o efeito. Cai bem...