Professional Documents
Culture Documents
Hugh C. Lauer
Adjunct Professor
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and
from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
CS-2303, C-Ter
m 2010
Polymorphism
class D: public B {
public
void m();
void p();
...
} // class D
CS-2303, C-Ter
m 2010
class D: public B {
public
void m();
Class D redefines method m()
void p();
...
} // class D
CS-2303, C-Ter
m 2010
Polymorphism
A reference to an object
A pointer to an object
CS-2303, C-Ter
m 2010
Polymorphism
CS-2303, C-Ter
m 2010
Polymorphism
class Shape {
to
d
o
eth ct
m
public:
he obje
t
s
voidccRotate();
es nd of
a
ki
o
t
t
e!
void
Draw();
h
l
d
d
g
i
an
er
h
Nee...
h
f
t
o
w
dra rdless
} ega
CS-2303, C-Ter
m 2010
Polymorphism
Polymorphism
CS-2303, C-Ter
m 2010
Polymorphism
Notes on virtual
If a method is declared virtual in a class,
it is automatically virtual in all derived
classes
Polymorphism
class Shape {
public:
virtual void Rotate();
virtual void Draw();
...
}
class Line: public Shape {
public:
void Rotate();
//Use base class Draw method
...
}
CS-2303, C-Ter
m 2010
Polymorphism
10
Example
Deitel & Deitel, 24.3
CommissionEmployee and
BasePlusCommissionEmployee
CS-2303, C-Ter
m 2010
Polymorphism
11
Polymorphism
The ability to declare functions/methods as
virtual is one of the central elements of
polymorphism in C++
Polymorphism: from the Greek having
multiple forms
In programming languages, the ability to assign a
different meaning or usage to something in different
contexts
CS-2303, C-Ter
m 2010
Polymorphism
12
13
Polymorphism
14
Questions?
CS-2303, C-Ter
m 2010
Polymorphism
15
Definitions
Concrete Classes
Classes used to instantiate objects
Must provide implementation for every member function they
define
CS-2303, C-Ter
m 2010
Polymorphism
16
Example
virtual void draw() const = 0;
"= 0" is known as a pure specifier.
Polymorphism
17
Polymorphism
18
Purpose
When it does not make sense for base class
to have an implementation of a function
Software design requires all concrete
derived classes to implement the function
Themselves
CS-2303, C-Ter
m 2010
Polymorphism
19
Polymorphism
20
CS-2303, C-Ter
m 2010
Polymorphism
21
Polymorphism
22
Questions?
CS-2303, C-Ter
m 2010
Polymorphism
23