CS 70

Key Points

Polymorphism

  • Polymorphism means ”many forms/types”. A function is polymorphic if it allows arguments of different types.
  • We've seen three types of polymorphism in C++:
    1. Subtype Polymorphism (inheritance).
    2. Parametric Polymorphism (templates).
    3. Ad-Hoc Polymorphism (overloading).

Inheritance and Subtypes

  • In C++, subtype polymorphism is used by creating base classes and derived classes.
  • Dynamic dispatch is when we figure out which implementation of a particular member function to call based on the actual type of the object at runtime, rather than the type of the variable.
  • By default, C++ classes do not use dynamic dispatch.
    • The author of a base class can request that behavior by using the keyword virtual in front of a member function in the class definition.
    • If a member function is declared virtual in a base class, then it's virtual for all of its derived classes.
    • When writing a derived class, you should make it clear that you're overriding a virtual member function by using the keyword override in the derived class's definition of the member function.

Pure Virtual Member Functions, Abstract Classes & Interfaces

  • A base class can also declare a member function to be pure virtual.
    • The base class doesn't implement the member function at all—derived classes are required to implement it.
    • A member function is declared to be pure virtual by adding = 0 to the end of its declaration in the base-class definition.
  • If a class has any pure virtual member functions, it is an abstract class and you cannot create an instance of it—you can only create instances of (non-abstract) classes that are derived from the abstract class.
  • If a class is abstract and it only specifies pure virtual functions, it is an interface class.

(When logged in, completion status appears here.)