To declare a class as a friend, you use the C++ friend keyword:
class ClassOne
{
public:
friend class BefriendedClass;
...
In this example,ClassOnehas declared BefriendedClassas its friend. This means that
BefriendedClassnow has full access to any of ClassOne’s members.
Listing 16.7 illustrates friendship by rewriting the example from Listing 16.6, making
PartsLista friend of PartNode. Note that this does not make PartNodea friend of
PartsList.
LISTING16.7 FriendClass Illustrated
0: //Listing 16.7 Friend Class Illustrated
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: “;
27: cout << itsPartNumber << endl;
28: }
29:
30: // **************** Car Part ************
31:
32: class CarPart : public Part
33: {
572 Day 16