programming techniques classes ii

90
Programming Programming Techniques Techniques Classes II Classes II Important Class Important Class Features Features Spring 2009 Spring 2009

Upload: mae

Post on 21-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Programming Techniques Classes II. Important Class Features Spring 2009. References. C++ How to Program, Deitel, Prentice Hall, 2003 by Pearson Education, Fourth Edition Object Oriented Programming in C++, Robert Lafore, Waite Group Press, 1995, Second Edition. Classes II. Agenda: - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Programming Techniques  Classes II

Programming Programming TechniquesTechniques Classes II Classes II

Important Class Important Class FeaturesFeatures

Spring 2009Spring 2009

Page 2: Programming Techniques  Classes II

ReferencesReferences

C++ How to Program, C++ How to Program,

Deitel, Prentice Hall, 2003 by Pearson Deitel, Prentice Hall, 2003 by Pearson Education, Fourth Edition Education, Fourth Edition

Object Oriented Programming in Object Oriented Programming in C++,C++,Robert Lafore, Waite Group Press, Robert Lafore, Waite Group Press,

1995, Second Edition1995, Second Edition

Page 3: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class The Container class

8.8. The iterator class The iterator class

Page 4: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Keyword constKeyword const Specify Specify object not modifiableobject not modifiable Compiler error if attempt to modify Compiler error if attempt to modify

const objectconst object ExampleExample

const Time noon( 12, 0, 0 );const Time noon( 12, 0, 0 ); Declares const object noon of class Time Declares const object noon of class Time Initializes to 12Initializes to 12

Page 5: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

const member functions const member functions Member functions for const objects must Member functions for const objects must

also be constalso be const Cannot modify objectCannot modify object

Specify const in both prototype and Specify const in both prototype and definitiondefinition

in Prototype:in Prototype: After parameter listAfter parameter list

in Definitionin Definition Before beginning left braceBefore beginning left brace

Constructors and destructors Cannot be const as

they Must be able to modify objects

Page 6: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 1Example 1

Page 7: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 1Example 1

Page 8: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 1Example 1

const functions do not modify objects.

Page 9: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 1Example 1

Declare noon a const object.

Note that non-const constructor can initialize const object.

Page 10: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 1Example 1

Attempting to invoke non-const member function on const object results in compiler error.

Attempting to invoke non-const member function on const object results in compiler error even if function does not modify object.

Page 11: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Const member functionsConst member functions CanCan be used for: be used for:

All class objectsAll class objects MustMust be used for: be used for:

Const class objectsConst class objects

Page 12: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Member Member initializerinitializer syntax syntax CanCan be used for: be used for:

All data membersAll data members MustMust be used for: be used for:

const data membersconst data members Data members that are referencesData members that are references

Page 13: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 2Example 2

Page 14: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 2Example 2

Page 15: Programming Techniques  Classes II

11 . .const objects and const const objects and const member functionsmember functions

Example 2Example 2

Page 16: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class The Container class

8.8. The iterator class The iterator class

Page 17: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

friend functions:friend functions: are are defined outsidedefined outside class’s scope class’s scope they have the they have the right to access right to access

non-public membersnon-public members

Page 18: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Declaring friendsDeclaring friends A functionA function F ( ) : by preceding function F ( ) : by preceding function

prototype with keyword friend inside classprototype with keyword friend inside class A classA class “classTwo” as friend of another “classTwo” as friend of another

class “class One”: by placing declaration class “class One”: by placing declaration of form:of form:

Example: Example: friend F ( ); friend F ( ); friend class ClassTwo;friend class ClassTwo;

inside ClassOne definitioninside ClassOne definition

Page 19: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Properties of friendshipProperties of friendship Friendship granted, not taken i.e.Friendship granted, not taken i.e.

Class B friend of class AClass B friend of class A Class A must explicitly declare class B Class A must explicitly declare class B

friendfriend Not symmetric Not symmetric

Class B friend of class AClass B friend of class A Class A not necessarily friend of class B Class A not necessarily friend of class B

Page 20: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Properties of friendship (cont.)Properties of friendship (cont.) Not transitive Not transitive

Class A friend of class B Class A friend of class B Class B friend of class CClass B friend of class C Class A not necessarily friend of Class A not necessarily friend of

Class CClass C

friendfriend

Page 21: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Example 1:Example 1:

Page 22: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Example 1:Example 1:NOT a member function!

Page 23: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Example 1:Example 1:

Page 24: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes Example 2: Example 2: A global function as friendA global function as friend

class Distance // English Distance classclass Distance // English Distance class

{ {

friendfriend Distance Add_Dist (Distance , Distance); Distance Add_Dist (Distance , Distance);

private:private:

int feet; float inches;int feet; float inches;

public:public:

Distance ( ) { } // constructor (no args)Distance ( ) { } // constructor (no args)

Distance (int ft, float in); ..........................Distance (int ft, float in); ..........................

Page 25: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes Example 2: function implementationExample 2: function implementation

Distance Add_Dist(Distance d2, Distance d3)Distance Add_Dist(Distance d2, Distance d3)

{{

float inches = d2.inches + d3.inches; int feet = 0; float inches = d2.inches + d3.inches; int feet = 0;

if (inches >= 12.0)if (inches >= 12.0)

{ {

inches -= 12.0; feet++; inches -= 12.0; feet++;

} }

feet += d2.feet + d3.feet; // add the feetfeet += d2.feet + d3.feet; // add the feet

return Distance (feet, inches); }return Distance (feet, inches); }

Non-member function!

Creating a member and returning its value!

Page 26: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes Example 2:Example 2:

main ( )main ( )

{{

Distance d1 (7, 5), d2 (3, 4);Distance d1 (7, 5), d2 (3, 4);

Distance d3;Distance d3;

d3 = d3 = Add_Dist ( d1, d2);Add_Dist ( d1, d2);

}}

How was it in the previous example of Add_dist? Compare!

Page 27: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Example 3: Example 3: class as a friend of another class as a friend of another classclass

class X {class X {

int a, b;int a, b;

friendfriend class F; class F;

public:public:

X(int i=1, int j =2 ) : a(i), b(j) X(int i=1, int j =2 ) : a(i), b(j) { }{ }

};};

Page 28: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes Example 3: Example 3: class as a friend of another class as a friend of another

classclass

class F {class F {

public:public:

void print( void print( X& xX& x ) { ) {

cout << "a is " << x . a << endl;cout << "a is " << x . a << endl;

cout << "b is " << x . b << endl;cout << "b is " << x . b << endl;

}}

};};

Page 29: Programming Techniques  Classes II

22 . .friend functions and friend functions and friend classesfriend classes

Example 3: Example 3: class as a friend of another class as a friend of another classclass

int main( ) {int main( ) {

X xobj;X xobj;

F fobj;F fobj;

fobj . Print ( xobj );fobj . Print ( xobj );

}}

Another alternative was to make only F::Print ( ) a friend to class X

Page 30: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class The Container class

8.8. The iterator class The iterator class

Page 31: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

CompositionComposition: an object inside another : an object inside another one ==> very strong one ==> very strong automaticautomatic relationshiprelationship

AggregationAggregation: an object inside another : an object inside another one, also. If implementation is done one, also. If implementation is done using using pointerspointers, then the outer object , then the outer object (may or may not be) is (may or may not be) is responsibleresponsible for for const and destruc. of inner objects.const and destruc. of inner objects.

AssociationAssociation: an object : an object with pointerwith pointer to to another object(s). Outer object is another object(s). Outer object is not not respresp. for const or destruc of the other . for const or destruc of the other object.object.

Page 32: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

CompositionComposition versus versus AggregationAggregation:: In In bothboth we talk about objects of one we talk about objects of one

class declared inside another class.class declared inside another class. AggregationAggregation differs from ordinary differs from ordinary

composition in that it composition in that it pointers pointers may may be used, whilebe used, while inin composition composition they they areare automatic automatic. .

In In bothboth, when the owning object is , when the owning object is destroyed, so are the contained destroyed, so are the contained objects. objects.

Page 33: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Composition versus AggregationComposition versus Aggregation

Example:Example: A university owns various A university owns various

departments (e.g., chemistry)departments (e.g., chemistry) CompositionComposition: If departments are : If departments are

implemented as static array implemented as static array AggregationAggregation: If departments are : If departments are

implemented as pointersimplemented as pointers

Page 34: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

What about What about AssociationAssociation ? ? An object with pointer to another An object with pointer to another

object(s). Outer object is NOT resp. object(s). Outer object is NOT resp. for const or destruc of the other for const or destruc of the other object.object.

Example:Example: AssociationAssociation: Each department has a : Each department has a

number of professors.number of professors. When university is deleted, professors When university is deleted, professors

are not deleted ( Refer to website notes)are not deleted ( Refer to website notes)

Page 35: Programming Techniques  Classes II

ExampleExample

Page 36: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Construction of member objectsConstruction of member objects Member objects are constructed in Member objects are constructed in

order of declarationorder of declaration Member objects are constructed Member objects are constructed

before the enclosing outer class before the enclosing outer class objects (host objects) objects (host objects)

Page 37: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example:

Page 38: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example:

Page 39: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Page 40: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example:

Page 41: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example:

Page 42: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example:

Page 43: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example:

Page 44: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Example:Example: Create Date objects to pass to Employee constructor.

Page 45: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Page 46: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Aggregation: Aggregation: As opposed to As opposed to compositioncomposition

class Sales_infoclass Sales_info

{ float amount;{ float amount;

Date ddmmyy;Date ddmmyy;

……………………

};};

Page 47: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Aggregation: Aggregation: As opposed to As opposed to compositioncomposition

class Sales_Personclass Sales_Person

{ Sales_info * sales;{ Sales_info * sales;

……………………

public:public:

Sales_Person (int num_sales = Sales_Person (int num_sales = 10);10);

~Sales_Person ( );~Sales_Person ( );

};};

Page 48: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Aggregation: Aggregation: As opposed to As opposed to compositioncomposition

Sales_Person :: SalesPerson ( int c = 10)Sales_Person :: SalesPerson ( int c = 10){{ sales = new sales_info [ c ];sales = new sales_info [ c ];}}

Sales_Person :: ~Sales_Person ( )Sales_Person :: ~Sales_Person ( ){{ delete [ ] Sales;delete [ ] Sales;}}

Page 49: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Association: Association: As opposed to As opposed to composition and aggregationcomposition and aggregation

class Prof;class Prof; // forward declaration// forward declaration

class Course {class Course {

char course_id [ 8 ]; …..char course_id [ 8 ]; …..

Prof * prof;Prof * prof;

public:public:

Course ( char* id, ….., Prof* p);Course ( char* id, ….., Prof* p);

~ Course ( );~ Course ( );

}}

Page 50: Programming Techniques  Classes II

33 . .Composition: Objects as Composition: Objects as Members of ClassesMembers of Classes

Association: Association: As opposed to As opposed to composition and aggregationcomposition and aggregation

Course :: Course ( char* id, ….., Prof* p)Course :: Course ( char* id, ….., Prof* p)

{ ……….{ ……….

prof = p;prof = p;

}}

~ Course ( )~ Course ( )

{ // { // No deletion of prof pointer!!No deletion of prof pointer!!

// He is still allowed to exist! // He is still allowed to exist! !!

}}

Page 51: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class The Container class

8.8. The iterator class The iterator class

Page 52: Programming Techniques  Classes II

44 . .Dynamic memory Dynamic memory managementmanagement Same operators:Same operators: new new andand delete delete

new new operatoroperator

e.g.:e.g.:Time *timePtr;Time *timePtr;

timePtr = new Time;timePtr = new Time; Creates object of proper size for Creates object of proper size for

type Timetype Time Calls default constructor for objectCalls default constructor for object Error if no space in memory for Error if no space in memory for

objectobject Returns pointer of specified typeReturns pointer of specified type

Page 53: Programming Techniques  Classes II

44 . .Dynamic memory Dynamic memory managementmanagement

Providing initializersProviding initializers double *ptr = new double *ptr = new

double( 3.14159 );double( 3.14159 ); Time *timePtr = new Time( 12, Time *timePtr = new Time( 12,

0, 0 );0, 0 ); Allocating arraysAllocating arrays

int *gradesArray = new int[ 10 ];int *gradesArray = new int[ 10 ]; Time *timesArray = new Time *timesArray = new

Time[5];Time[5];

Page 54: Programming Techniques  Classes II

44 . .Dynamic memory Dynamic memory managementmanagement

deletedelete Destroy dynamically allocated Destroy dynamically allocated

object and free spaceobject and free space e.g.:e.g.:

delete timePtr;delete timePtr; Operator deleteOperator delete Calls destructorCalls destructor for object for object Deallocates memory associated Deallocates memory associated

with objectwith object Memory can be reused to Memory can be reused to

allocate other objectsallocate other objects

Page 55: Programming Techniques  Classes II

44 . .Dynamic memory Dynamic memory managementmanagement

Deallocating arraysDeallocating arrays e.g.:e.g.:

delete [ ] gradesArray;delete [ ] gradesArray; Deallocates array to which Deallocates array to which

gradesArray pointsgradesArray points If pointer to array of objectsIf pointer to array of objects

First First calls destructorcalls destructor for each for each object in arrayobject in array

Then deallocates memoryThen deallocates memory

Page 56: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class The Container class

8.8. The iterator class The iterator class

Page 57: Programming Techniques  Classes II

55.. thisthis Pointer Pointer

Allows object to access own addressAllows object to access own address Not part of object itself Not part of object itself Implicit argument to Implicit argument to non-staticnon-static

member function callmember function call Implicitly reference member data Implicitly reference member data

and functions and functions Type of this pointer depends on Type of this pointer depends on

Type of object Type of object

Page 58: Programming Techniques  Classes II

5. thisthis Pointer Pointer Type of this pointer depends on whether Type of this pointer depends on whether

member function is const or not:member function is const or not: In In non-constnon-const member function of Employee member function of Employee

this has type: this has type: Employee * constEmployee * const

i.e. i.e. Constant pointerConstant pointer to non-constant to non-constant Employee object Employee object

In In constconst member function of Employee this member function of Employee this has type: has type: const Employee * constconst Employee * const

i.e. i.e. Constant pointerConstant pointer to constant Employee to constant Employee objectobject

Page 59: Programming Techniques  Classes II

55.. thisthis Pointer Pointer Example:Example:

Page 60: Programming Techniques  Classes II

55.. thisthis Pointer Pointer Example:Example: Implicitly use this pointer;

only specify name of data member (x).

Explicitly use this pointer with arrow operator.

Explicitly use this pointer; dereference this pointer first, then use dot operator.

Page 61: Programming Techniques  Classes II

55.. thisthis Pointer Pointer CascadedCascaded member function calls are member function calls are

possible using this!possible using this! Multiple functions invoked in same Multiple functions invoked in same

statement (Casacded member function statement (Casacded member function calls)calls)

Function returns reference pointer to same Function returns reference pointer to same object { return *this; } object { return *this; }

Other functions operate on that pointerOther functions operate on that pointer Functions that do not return references Functions that do not return references

must be called lastmust be called last

Will be explained more in operator moverloading!

Page 62: Programming Techniques  Classes II

55.. thisthis Pointer Pointer Example:Example:

Cascade member function calls; recall dot operator associates from left to right.

What is the return value of setHour, setMinute and setSecond?

Page 63: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class The Container class

8.8. The iterator class The iterator class

Page 64: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

StaticStatic class variables are accessible class variables are accessible through any object of classthrough any object of class

publicpublic static static variables can also be variables can also be accessed using binary scope accessed using binary scope resolution operator(::)resolution operator(::)

Employee Employee :::: count count private private static static variables can only be variables can only be

accessed via public static member accessed via public static member function function (even when no class member (even when no class member objects exist)objects exist)

Page 65: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

To call public static member To call public static member function combine class name function combine class name with binary scope resolution with binary scope resolution operator (::) and function operator (::) and function namename

Employee Employee :::: getCount( )getCount( )

Page 66: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

static member functions and static member functions and static data members static data members existexist independent of objectsindependent of objects, hence:, hence:

Static member functions cannot Static member functions cannot access non-static data or access non-static data or functions functions

No this pointer for static No this pointer for static functionsfunctions

Page 67: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

Example:Example:

Compare with previous declaration for Name strings!

Page 68: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

in .cpp filein .cpp file Initialize static data member exactly once at file scope.

static member function accesses static data member count.

Page 69: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

constructor in .cpp fileconstructor in .cpp file

Page 70: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

.cpp file:.cpp file:

Operator delete deallocates memory.

Use static data member to store total count of employees.

Page 71: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

In mainIn main

new operator dynamically allocates space.

static member function can be invoked on any object of class.

Page 72: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

main (cont.)main (cont.)

Operator delete deallocates memory.

static member function invoked using binary scope resolution operator (no existing class objects).

Page 73: Programming Techniques  Classes II

66 . .static data members and static data members and static functionsstatic functions

Output:Output:

Page 74: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class and the iterator class The Container class and the iterator class

8.8. Proxy classes and forward declarationProxy classes and forward declaration

Page 75: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

Composition that is used to store Composition that is used to store several instances of the several instances of the composited data type is referred composited data type is referred to as containment. to as containment.

Examples are:Examples are: arraysarrays linked listslinked lists binary trees ….binary trees ….

Page 76: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

These are classes that hide These are classes that hide implemen-tation details from clientsimplemen-tation details from clients

Example: Example: stackstack data structure: Client data structure: Client only wants LIFO data structure, he only wants LIFO data structure, he does not care how stack implementeddoes not care how stack implemented

Data elements added (pushed) onto topData elements added (pushed) onto top Data elements removed (popped) from Data elements removed (popped) from

toptop Last-in, first-out (LIFO) data structureLast-in, first-out (LIFO) data structure

Page 77: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

Example 1: An array abstract data type Example 1: An array abstract data type could includecould include

Subscript range checking Subscript range checking Arbitrary range of subscripts instead of Arbitrary range of subscripts instead of

having to start with 0having to start with 0 Array assignment Array assignment Array comparison Array comparison Arrays that know their sizes Arrays that know their sizes Arrays that expand dynamically to Arrays that expand dynamically to

accommodate more elementsaccommodate more elements

Page 78: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

Example 2: Queue Abstract Example 2: Queue Abstract Data TypeData Type

First in, first out (FIFO)First in, first out (FIFO) Enqueue: Put items in queue Enqueue: Put items in queue

one at a timeone at a time Dequeue: Remove items from Dequeue: Remove items from

queue one at a timequeue one at a time

Page 79: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

Queue ADTQueue ADT Implementation hidden from Implementation hidden from

clientsclients Clients may not manipulate data Clients may not manipulate data

structure directly structure directly Only queue member functions Only queue member functions

can access internal datacan access internal data

Page 80: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

C++ provides mechanisms C++ provides mechanisms for creating and for creating and implementing abstract implementing abstract data typedata type

Page 81: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

Container classes (collection classes) Container classes (collection classes) are designed to hold collections of are designed to hold collections of objectsobjects

Common services:Common services: Insertion, deletion, searching, sorting, or Insertion, deletion, searching, sorting, or

testing an itemtesting an item Examples:Examples:

Arrays, stacks, queues, trees and linked Arrays, stacks, queues, trees and linked listslists

Page 82: Programming Techniques  Classes II

77 . .The Container class and The Container class and the iterator classthe iterator class

Iterator objects (iterators)Iterator objects (iterators) Returns next item of collection or Returns next item of collection or

performs some action on next itemperforms some action on next item Can have several iterators per container Can have several iterators per container

e.g.e.g. Book with multiple bookmarksBook with multiple bookmarks

Each iterator maintains own Each iterator maintains own “position”“position”

Discussed further in Chapter 20Discussed further in Chapter 20

Page 83: Programming Techniques  Classes II

Classes IIClasses II

Agenda:Agenda:1.1. const objects and const member functionsconst objects and const member functions

2.2. friend functions and friend classesfriend functions and friend classes

3.3. Composition: Objects as Members of ClassesComposition: Objects as Members of Classes

4.4. Dynamic Memory Management with Dynamic Memory Management with Operators new and deleteOperators new and delete

5.5. thisthis pointer pointer

6.6. static data members and static functionsstatic data members and static functions

7.7. The Container class and the iterator class The Container class and the iterator class

8.8. Proxy classes and forward declarationProxy classes and forward declaration

Page 84: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

Proxy classProxy class Hide implementation details of Hide implementation details of

another classanother class Knows only public interface of Knows only public interface of

class being hiddenclass being hidden Enables clients to use class’s Enables clients to use class’s

services without giving access to services without giving access to class’s implementationclass’s implementation

Page 85: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

Example: class Example: class implementationimplementation

Page 86: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

class implementation (cont.)class implementation (cont.)

Page 87: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

The Implementation classThe Implementation class

Provide same public interface as class Implementation; recall setValue and getValue only public member functions.

Pointer to Implementation object requires forward class declaration.

Page 88: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

The interface implementationThe interface implementation

Proxy class Interface includes header file for class Implementation.

Maintain pointer to underlying Implementation object.

Invoke corresponding function on underlying Implementation object.

Page 89: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

The interface The interface implementation(cont.)implementation(cont.)Invoke corresponding

function on underlying Implementation object.

Deallocate underlying Implementation object.

Page 90: Programming Techniques  Classes II

88 . .Proxy classes and forward Proxy classes and forward declarationdeclaration

main ( )main ( )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.