Sams Teach Yourself C++ in 21 Days

(singke) #1
In Review 501

On lines 212–258, the Insert()method takes a pointer to a Part, creates a PartNodefor
it, and adds the Partto the list, ordered by PartNumber.
Iterate()on lines 202–210 takes a pointer to a member function of Part, which takes
no parameters, returns void, and is const. It calls that function for every Partobject in
the list. In the sample program, this is called on Display(), which is a virtual function,
so the appropriate Display()method is called based on the runtime type of the Part
object called.
On lines 170–184, the bracket operator is overloaded. Operator[]allows direct access to
the Partat the offset provided. Rudimentary bounds checking is provided; if the list is
NULLor if the offset requested is greater than the size of the list,NULLis returned as an
error condition.
Note that in a real program, these comments on the functions would be written into the
class declaration.
The driver program starts on line 260. The PartListobject is created on line 263.
On line 277, the user is repeatedly prompted to choose whether to enter a car part or an
airplane part. Depending on the choice, the right value is requested, and the appropriate
part is created. After it is created, the part is inserted into the list on line 293.
The implementation for the Insert()method of PartsListis on lines 212–258. When
the first part number is entered, 2837 ,a CarPartwith that part number and the model
year 90 is created and passed in to LinkedList::Insert().
On line 214, a new PartNodeis created with that part, and the variable Newis initialized
with the part number. The PartsList’s itsCountmember variable is incremented on
line 220.
On line 222, the test that pHeadis NULL will evaluate true. Because this is the first
node, it is true that the PartsList’s pHeadpointer has zero. Thus, on line 224,pHeadis
set to point to the new node and this function returns.
The user is prompted to enter a second part, and this time an AirPlanepart with part
number 37 and engine number 4938 is entered. Once again,PartsList::Insert()is
called, and once again,pNodeis initialized with the new node. The static member vari-
able itsCountis incremented to 2 , and pHeadis tested. Because pHeadwas assigned last
time, it is no longer null and the test fails.
On line 230, the part number held by pHead, 2837 , is compared against the current part
number, 378. Because the new one is smaller than the one held by pHead, the new one
must become the new head pointer, and the test on line 230 is true.

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

Free download pdf