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:
- We would like to be able to print out and read every object we
use in our monopoly project. By deriving every object from the
Base class, we enforce this intention.
- Even if reading and writing things may seem simple at first,
doing it properly is difficult. Especially the reading is
hard, since we have to be able to deal with any kind of user
input. By factoring out this functionality, we can define a common
format (a read syntax, for LISP fans) for all our objects.
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
- Copy the code from exercise 1 and
exercise 2. Merge the two main.C programs
into one program. Rewrite the Makefile.
- Rename the read() and write() functions in the
Dice and Account classes to readContents()
and writeContents(). Be sure to declare them virtual.
- Create the header file Base.h.
- Derive Account and Dice from
Base. Be sure to include the Base.h file in the
header files of Dice.h and Account.h.
- 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