2003 Prentice Hall, Inc. All Rights Reserved
2003 Prentice Hall, Inc. All Rights Reserved
Object-Oriented Programming:
Polymorphism
Outline
10.1 Introduction
10.2 Relationships Among Objects in an Inheritance Hierarchy
10.2.1 Invoking Base-Class Functions from Derived-Class
Objects
10.2.2 Aiming Derived-Class Pointers at Base-Class Objects
10.2.3 Derived-Class Member-Function Calls via Base-Class
Pointers
10.2.4 Virtual Functions
10.3 Polymorphism Examples
10.4 Type Fields and switch Structures
10.5 Abstract Classes
10.6 Case Study: Inheriting Interface and Implementation
10.7 Polymorphism, Virtual Functions and Dynamic Binding “Under the
Hood”
10.8 Virtual Destructors
10.1 Introduction
• Polymorphism
– “Program in the general”
– Treat objects in same class hierarchy as if all base class
– Virtual functions and dynamic binding
• Will explain how polymorphism works
– Makes programs extensible
• New classes added easily, can still be processed
• In our examples
– Use abstract base class Shape
• Defines common interface (functionality)
• Point, Circle and Cylinder inherit from Shape
– Class Employee for a natural example
• Example
– Redo Point, Circle example with virtual functions
– Base-class pointer to derived-class object
• Will call derived-class function
• Polymorphism
– Same message, “print”, given to many objects
• All through a base pointer
– Message takes on “many forms”
• Summary
– Base-pointer to base-object, derived-pointer to derived
• Straightforward
– Base-pointer to derived object
• Can only call base-class functions
– Derived-pointer to base-object
• Compiler error
• Allowed if explicit cast made (more in section 10.9)
• Examples
– Suppose Rectangle derives from Quadrilateral
• Rectangle more specific Quadrilateral
• Any operation on Quadrilateral can be done on
Rectangle (i.e., perimeter, area)
• Suppose designing video game
– Base class SpaceObject
• Derived Martian, SpaceShip, LaserBeam
• Base function draw
– To refresh screen
• Screen manager has vector of base-class pointers to objects
• Send draw message to each object
• Same message has “many forms” of results
• Abstract classes
– Sole purpose: to be a base class (called abstract base classes)
– Incomplete
• Derived classes fill in "missing pieces"
– Cannot make objects from abstract class
• However, can have pointers and references
• Concrete classes
– Can instantiate objects
– Implement all functions they define
– Provide specifics
center=[x,y];
Cylinder 2r +2rh
2
r h
2
"Cylinder" radius=r;
height=h
Employee
BasePlusCommissionEmployee
• Keyword typeid
– Header <typeinfo>
– Usage: typeid(object)
• Returns type_info object
• Has information about type of operand, including name
• typeid(object).name()
fig10_33.cpp
commission employee: Sue Jones
output (1 of 1)
social security number: 222-22-2222
earned $600.00