programming techniques classes ii

Post on 21-Jan-2016

16 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

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

Programming Programming TechniquesTechniques Classes II Classes II

Important Class Important Class FeaturesFeatures

Spring 2009Spring 2009

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

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

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

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

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

Example 1Example 1

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

Example 1Example 1

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

Example 1Example 1

const functions do not modify objects.

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.

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.

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

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

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

Example 2Example 2

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

Example 2Example 2

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

Example 2Example 2

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

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

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

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

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

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

Example 1:Example 1:

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

Example 1:Example 1:NOT a member function!

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

Example 1:Example 1:

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); ..........................

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!

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!

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) { }{ }

};};

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;

}}

};};

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

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

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.

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.

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

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)

ExampleExample

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)

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

Example:Example:

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

Example:Example:

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

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

Example:Example:

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

Example:Example:

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

Example:Example:

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

Example:Example:

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

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

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

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;

……………………

};};

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 ( );

};};

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;}}

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 ( );

}}

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! !!

}}

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

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

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];

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

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

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

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

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

55.. thisthis Pointer Pointer Example:Example:

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.

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!

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?

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

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)

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

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

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

Example:Example:

Compare with previous declaration for Name strings!

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.

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

constructor in .cpp fileconstructor in .cpp file

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.

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.

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

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

Output:Output:

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

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 ….

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

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

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

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

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

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

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

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

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

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

Example: class Example: class implementationimplementation

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

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

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.

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.

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.

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.

top related