13. Object-Oriented Programming: Polymorphism

Objectives

In this chapter you'll learn:

  • What polymorphism is, how it makes programming more convenient and how it makes systems more extensible and maintainable.

  • To declare and use virtual functions to effect polymorphism.

  • The distinction between abstract and concrete classes.

  • To declare pure virtual functions to create abstract classes.

  • How to use runtime type information (RTTI) with downcasting, dynamic_cast, typeid and type_info.

  • How C++ implements virtual functions and dynamic binding "under the hood."

  • How to use virtual destructors to ensure that all appropriate destructors run on an object.

One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.

John Ronald Reuel Tolkien

The silence often of pure innocence

Persuades when speaking fails.

William Shakespeare

General propositions do not decide concrete cases.

Oliver Wendell Holmes

A philosopher of imposing stature doesn't think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives.

Alfred North Whitehead

Outline

13.1 Introduction
13.2 Polymorphism Examples
13.3 Relationships Among Objects in an Inheritance Hierarchy
  13.3.1 Invoking Base-Class Functions from Derived-Class Objects
  13.3.2 Aiming Derived-Class Pointers at Base-Class Objects
  13.3.3 Derived-Class Member-Function Calls via Base-Class Pointers
  13.3.4 Virtual Functions
  13.3.5 Summary of the Allowed Assignments Between Base-Class and Derived-Class Objects and Pointers
13.4 Type Fields and switch Statements
13.5 Abstract Classes and Pure virtual Functions
13.6 Case Study: Payroll System Using Polymorphism
  13.6.1 Creating Abstract Base Class Employee
  13.6.2 Creating Concrete Derived Class SalariedEmployee
  13.6.3 Creating Concrete Derived Class HourlyEmployee
  13.6.4 Creating Concrete Derived Class CommissionEmployee
  13.6.5 Creating Indirect Concrete Derived Class BasePlusCommissionEmployee
  13.6.6 Demonstrating Polymorphic Processing
13.7 (Optional) Polymorphism, Virtual Functions and Dynamic Binding "Under the Hood"
13.8 Case Study: Payroll System Using Polymorphism and Runtime Type Information with Downcasting, dynamic_cast, typeid and type_info
13.9 Virtual Destructors
13.10 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System
13.11 Wrap-Up