802 Week 3
exceptions; they serve as flags to the catchstatements, which print out a very simple
warning and then exit. A more robust program might pass these exceptions by reference
and then extract context or other data from the exception objects in an attempt to recover
from the problem.
On line 45, the abstract base class Partis declared exactly as it was in Week 2. The only
interesting change here is in the nonclass member operator<<(), which is declared on
lines 70–74. Note that this is neither a member of Partnor a friend of Part, it simply
takes a Partreference as one of its arguments.
You might want to have operator<<take a CarPartand an AirPlanePartin the hopes
that the correct operator<<would be called, based on whether a car part or an airplane
part is passed. Because the program passes a pointer to a part, however, and not a pointer
to a car part or an airplane part, C++ would have to call the right function based on the
real type of one of the arguments to the function. This is called contravariance and is not
supported in C++.
You can only achieve polymorphism in C++ in two ways: function polymorphism and
virtual functions. Function polymorphism won’t work here because in every case you are
matching the same signature: the one taking a reference to a Part.
Virtual functions won’t work here because operator<<is not a member function of
Part. You can’t make operator<<a member function of Partbecause you want to
invoke
cout << thePart
and that means that the actual call would be to cout.operator<<(Part&), and coutdoes
not have a version of operator<<that takes a Partreference!
To get around this limitation, the Week 3 program uses just one operator<<, taking a
reference to a Part. This then calls Display(), which is a virtual member function, and
thus the right version is called.
On lines 130–143,Nodeis defined as a template. It serves the same function as Nodedid
in the Week 2 Review program, but this version of Nodeis not tied to a Partobject. It
can, in fact, be the node for any type of object.
Note that if you try to get the object from Node, and there is no object, this is considered
an exception, and the exception is thrown on line 175.
On lines 182 and 183, a generic Listclass template is defined. This Listclass can hold
nodes of any objects that have unique identification numbers, and it keeps them sorted in
ascending order. Each of the list functions checks for exceptional circumstances and
throws the appropriate exceptions as required.
28 0672327112_w3_wir.qxd 11/19/04 12:30 PM Page 802