Inheritance/Polymorphism  «Prev  Next»
Lesson 1

C++ Inheritance and Pure Polymorphism

This module explores the fundamentals of inheritance and pure polymorphism, including the use of derived classes and virtual functions to create a class hierarchy.
You will learn:
  1. What inheritance is and why it is so important to the object-oriented programming paradigm
  2. What virtual member functions are and how they are used
  3. How to derive a class from a base class and create a class hierarchy
  4. How public inheritance implements an ISA relationship between a derived class and the base class
  5. How a reference to the derived class may be implicitly converted to a reference to the public base class
  6. What pure virtual functions are and why they are useful in creating abstract base classes
  7. The uses of the C++-specific cast operators
  8. How to use Runtime Type Identification (RTTI) to safely determine the type pointed at by a base class pointer at runtime
  9. How to code exceptions to catch unexpected conditions

Model Variation in Object Behavior

In this section you will see an even more powerful application of inheritance: to model variation in object behavior. If you look into the main function of clocks2.cpp, you will find that there was quite a bit of repetitive code. It would be nicer if all three clocks were collected in a vector and one could use a loop to print the clock values:

vector <Clock> clocks;
clocks[0] = Clock(true);
clocks[1] = TravelClock(true, "Rome", 9);
clocks[2] = TravelClock(false, "Tokyo", -7);
for (int i = 0; i < clocks.size(); i++)
{
cout << clocks[i].get_location() << " time is "
<< clocks[i].get_hours() << ":"
<< setw(2) << setfill('0')
<< clocks[i].get_minutes()
<< setfill(' ') << "\n";
}