Main

Week 8 (cont.)

Reference: Chapter 15

Polymorphism and Virtual Functions

Modern object-oriented (OO) languages provide 3 capabilities:

  • encapsulation
  • inheritance
  • polymorphism

which can improve the design, structure and reusability of code.

Here, we'll explore in more detail how polymorphism can be used in C++.

What is polymorphism?

In programming languages, polymorphism means that some code or operations or objects behave differently in different contexts.

For example, the + (plus) operator in C++:

4 + 5integer addition
3.14 + 2.0floating point addition
s1 + "bar"string concatenation

This type of polymorphism is accomplished through operator overloading, but polymorphism is not limited to operators.

C++ actually has four kinds of polymorphism:

  • Subtype polymorphism, also known as runtime polymorphism.
  • Parametric polymorphism, also known as compile-time polymorphism.
  • Ad-hoc polymorphism, also known as overloading.
  • Coercion, also known as (implicit or explicit) casting.

More about these types: http://www.catonmat.net/blog/cpp-polymorphism/

The rest of this lecture will go through several examples as part of the code in week8 of the lecture code repository -- additional notes will be posted after lecture.

Green Marinee theme adapted by David Gilbert, powered by PmWiki