Computing Concepts with C++ Essentials
Laboratory Notebook
Chapter 14 - Inheritance and Polymorphism

Cay S. Horstmann
Geof Pawlicki


Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience with


P1. Inheritance

Consider using the following Card class as a base class to implement a hierarchy of related classes:

Class Data
IDcard ID number
Calling Card Card number, PIN
DriverLicense Expiration date
class Card
{
public:
   Card();
   Card(string n);
   virtual bool is_expired() const; 
   virtual void print() const; 
private:
   string name;
};

Card::Card()
{  name = "";
}

Card::Card(string n)
{  name = n;
}

Card::is_expired()
{   return false;
}

Write definitions for each of the derived classes. For each derived class, supply private data members and the declarations (but not the definitions) of the constructors and the print function:


P2. Calling the Base-Class constructor

Implement constructors for each of the three derived classes. Each constructor needs to call the base class constructor to set the name.


P3. Virtual Functions

Supply the implementation of a virtual print function for the card class and corresponding overloaded functions in each of the other three derived classes. The derived class functions need to call the base class print to print the name of the cardholder.

Devise another class, Billfold, which contains a vector<Card*>, a member function add_card(Card*) and a member function print_cards(). Of course, print_cards invokes the virtual print function on each card.

Have a main function populate a Billfold object with Card* objects, and then call print_cards.

Show the output of your test run.

Is print_cards a virtual function? Explain.

The Card base class defines a member function is_expired which always returns false. This method is appropriate for the ID card and the phone card because those cards don't expire. But it is not appropriate for the driver license. Supply a member function DriverLicense::is_expired() that gets the current time and checks if the driver license is already expired.

Note that you should not redefine is_expired for the other card types. They simply inherit the base class function.

Add a member function print_expired_cards to the Billfold which queries each card whether it is expired and only prints those that are expired.

Write a main program that populates a billfold with an ID card, a phone card and an expired driver license. Then call the print_expired_cards function.

Show the output of your test run.


Don't forget to send your answers when you're finished.