BIG C++ Cay Horstmann & Timothy Budd
Laboratory Notebook Chapter 11 - Inheritance
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.
To gain experience with
Consider using the following Card class as a base class to implement a hierarchy of related classes:
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; } bool Card::is_expired() const { 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:
/* paste code here */
Implement constructors for each of the three derived classes. Each constructor needs to call the base class constructor to set the name.
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.
/* paste program here */
Show the output of your test run.
/* paste output here */
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 do not expire. But it is not appropriate for the driver's license. Supply a member function DriverLicense::is_expired() that gets the current time and checks if the driver's 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.
Do not forget to send your answers when you are finished.