An important use of polymorphism is the writing of non-member functions
to deal with all classes in an inheritance hierarchy.
This is accomplished by defining the function parameters as
pointers (or references) to base class objects, then having the caller
pass in a pointer (or reference) to a derived class object.
Dynamic binding calls the appropriate method.
These functions are often referred to as polymorphic functions.
NOTE THE CODE REUSE -- This function can call new code
without being rewritten when
new derived classes are implemented. This is "old" code
calling "new" code.
A non-member drawShape( ) function
Note that this function's parameter is a pointer to a Shape,
the base class of the inheritance heirarchy.
void DrawShape ( Shape *pShape )
cout << "I am ";
pShape -> ObjectID ( );
pShape ->Draw ( );
if ( something bad )
pShape->Error ( );
What is the output if DrawShape( ) is passed:
This version of DrawShape( ) uses pass by reference
void drawShape (Shape& shape)
cout << "I am " ;
shape.ObjectID ( );
shape.Draw ( );
if (something bad)
shape.Error ( );
What is the output if DrawShape is passed:
- a pointer to a Circle object?
- a pointer to a Rectangle object?
- a Circle object?
- a Rectangle object?
Don't Pass by Value
A function that has a base class parameter passed by value should only be
used with base class objects because:
- The function isn't polymorphic. Polymorphism only occurs with parameters passed by pointer or reference.
- Even though a derived class object can be passed to such a function
(a D is-a B), none of the derived class methods or data members can be used
in that function.
Last Modified: Monday, 28-Aug-2006 10:16:04 EDT