Polymorphism
Polymorphism
1
Object-Oriented Concept
Encapsulation
ADT, Object
Inheritance
Derived object
Polymorphism
Each object knows what it is
2
Polymorphism – An Introduction
noun, the quality or state of being able to assume
different forms - Webster
An essential feature of an OO Language
It builds upon Inheritance
3
Before we proceed….
Inheritance – Basic Concepts
Class Hierarchy
Code Reuse, Easy to maintain
Type of inheritance : public, private
Function overriding
4
Class Interface Diagram
ExtTime class Time class
Set Set
CLIENT CODE
6
Static Binding
When the type of a formal parameter is a parent class, the argument
used can be:
7
Can we do better?
CLIENT CODE
8
Polymorphism – An Introduction
9
Dynamic Binding
10
Virtual Member Function
// SPECIFICATION FILE ( time.h )
class Time
{
public :
. . .
11
This is the way we like to see…
void Print (Time * someTime )
{
cout << “Time is “ ;
someTime->Write ( ) ;
cout << endl ;
} OUTPUT
Time *timeptr;
timeptr = &startTime;
Print ( timeptr ) ; Time::write()
timeptr = &endTime;
Print ( timeptr ) ; ExtTime::write()
12
Virtual Functions
Virtual Functions overcome the problem of run time object
determination
Keyword virtual instructs the compiler to use late binding and delay
the object interpretation
How ?
Define a virtual function in the base class. The word virtual appears
14
Abstract Classes & Pure Virtual Functions
Some classes exist logically but not physically.
Example : Shape
Shape s; // Legal but silly..!! : “Shapeless shape”
Shape makes sense only as a base of some classes derived from
it. Serves as a “category”
Hence instantiation of such a class must be prevented
Circle Triangle
16
A pure virtual function not defined in the derived class
remains a pure virtual function.
Hence derived class also becomes abstract
Rectangle r; // Valid
Circle c; // error : variable of an abstract class
17
Pure virtual functions : Summary
18
Summary ..continued
It is still possible to provide definition of a pure virtual function in
the base class
The class still remains abstract and functions must be redefined in
the derived classes, but a common piece of code can be kept there to
facilitate reuse
In this case, they can not be declared inline
20