Previous Exercise | Next Exercise | Solution | Lecture | Top Level
For this exercise, please refer to the model solutions of exercise 1 and exercise 2.

Context

As you can see, both the Dice and the Account class have read and write member functions. In this exercise, we will factor out the read and write functions. We do this because:

For this to work, we divide the task of reading and writing into two parts: The form and the content.

Every object will look like this:

begin
  <data>
end
The Base class will read and write the begin-end pair, and the specialized classes will read the contents. Since Base::read() and Base::write() will want to use the specialized versions of readContents() and writeContents(), these will be declared as virtual. So this is what the header file Base.h looks like:
class Base {
public:

  // These functions will be used in read() and write(),
  // but defined by the derived classes:
  virtual void readContents() = 0;
  virtual void writeContents() = 0;

  // These functions are implemented by the Base class:
  void read();
  void write();
};

Basic Exercises

  1. Copy the code from exercise 1 and exercise 2. Merge the two main.C programs into one program. Rewrite the Makefile.
  2. Rename the read() and write() functions in the Dice and Account classes to readContents() and writeContents(). Be sure to declare them virtual.
  3. Create the header file Base.h.
  4. Derive Account and Dice from Base. Be sure to include the Base.h file in the header files of Dice.h and Account.h.
  5. Implement the functions read() and write() using the functions readContents() and writeContents(). Make sure you check (using strcmp()) that you are actually reading the string begin and end. Print out an error message and exit the program if not.

Advanced Exercise

Instead of using begin to mark the beginning of an object read, use the object's classname. Define and implement a virtual function className() that returns a char* pointing to the name of it's class, and use it in the read() and write() functions.

This will allow us to detect which object we are reading.


Christian Goetze