Sams Teach Yourself C++ in 21 Days

(singke) #1
repeat. The PartsCataloghas unique entries that are not ordered. The fifth member of
the PartsCatalogis not part number 5.
Certainly, it would have been possible to inherit publicly from PartsListand then over-
ride Insert()and the offset operators ([]) to do the right thing, but then you would have
changed the essence of the PartsListclass. Instead, you’ll build a PartsCatalogthat
has no offset operator, does not allow duplicates, and defines the operator+to combine
two sets.
The first way to accomplish this is with aggregation. The PartsCatalogwill delegate list
management to an aggregated PartsList. Listing 16.5 illustrates this approach.

LISTING16.5 Delegating to an Aggregated PartsList
0: // Listing 16.5 Delegating to an Aggregated PartsList
1:
2: #include <iostream>
3: using namespace std;
4:
5: // **************** Part ************
6:
7: // Abstract base class of parts
8: class Part
9: {
10: public:
11: Part():itsPartNumber(1) {}
12: Part(int PartNumber):
13: itsPartNumber(PartNumber){}
14: virtual ~Part(){}
15: int GetPartNumber() const
16: { return itsPartNumber; }
17: virtual void Display() const =0;
18: private:
19: int itsPartNumber;
20: };
21:
22: // implementation of pure virtual function so that
23: // derived classes can chain up
24: void Part::Display() const
25: {
26: cout << “\nPart Number: “ << itsPartNumber << endl;
27: }
28:
29: // **************** Car Part ************
30:
31: class CarPart : public Part
32: {
33: public:
34: CarPart():itsModelYear(94){}
35: CarPart(int year, int partNumber);

554 Day 16

Free download pdf