Sams Teach Yourself C++ in 21 Days

(singke) #1
500 Week 2

Class Partis declared on lines 27–37, and consists of a part number and some accessors.
Presumably, this class could be fleshed out to hold other important information about the
parts, such as what components they are used in, how many are in stock, and so forth.
Partis an abstract data type, enforced by the pure virtual function Display().
Note that Display()does have an implementation, on lines 41–44. It is the designer’s
intention that derived classes will be forced to create their own Display()method, but
can chain up to this method as well.
Two simple derived classes,CarPartand AirPlanePart, are provided on lines 48–60
and 70–82, respectively. Each provides an overridden Display()method, which does, in
fact, chain up to the base class Display()method.
The class PartNodeon lines 90–101 serves as the interface between the Partclass and
the PartListclass. It contains a pointer to a part and a pointer to the next node in the
list. Its only methods are to get and set the next node in the list and to return the Partto
which it points.
The intelligence of the list is, appropriately, in the class PartsList, whose declaration is
on lines 133–148. PartsListkeeps a pointer to the first element in the list (pHead) and
uses that to access all other methods by walking the list. Walking the list means asking
each node in the list for the next node, until you reach a node whose next pointer is NULL.
This is only a partial implementation; a fully developed list would provide either greater
access to its first and last nodes, or would provide an iterator object, which allows clients
to easily walk the list.
PartsListnonetheless provides a number of interesting methods, which are listed in
alphabetical order. This is often a good idea, as it makes finding the functions easier.
Find()takes a PartNumberand an int(lines 186–200). If the part corresponding to
PartNumberis found, it returns a pointer to the Partand fills the intwith the position of
that part in the list. If PartNumberis not found, it returns NULL, and the position is mean-
ingless.
GetCount()returns the number of elements in the list (line 140). PartsListkeeps this
number as a member variable,itsCount, though it could, of course, compute this num-
ber by walking the list.
GetFirst()returns a pointer to the first Partin the list, or returns NULLif the list is
empty (line 162–168).

19 0672327112_w2_wir.qxd 11/19/04 12:28 PM Page 500

Free download pdf