- friend function
- Defined outside class's scope
- Right to access non-public members
- Declaring friends
- Function; Precede function prototype with keyword friend
- All member functions of class ClassTwo as friends of class ClassOne
- Place declaration of form; friend class ClassTwo;
- in ClassOne definition
- Properties of friendship
- Friendship granted, not taken
- Class B friend of class A; Class A must explicitly declare class B friend
- Not symmetric
- Class B friend of class A
- Class A not necessarily friend of class B
- Not transitive
- Class A friend of class B
- Class B friend of class C
- Class A not necessarily friend of Class C
The program of Figs. 15-16 (top) defines friend function setX to set the private data member x of class Count. Friend declaration can appear anywhere in the class. The program of Figs. 16 (bottom) -17 demonstrates the error messages produced by the compiler when nonfriend function cannotSetX is called to modify private data member x.
Figure 15:
Friends can access private members of the class.
|
Figure 16:
Nonfriend/nonmember functions cannot access private members. (part 1 of 2)
|
Figure 17:
Nonfriend/nonmember functions cannot access private members. (part 2 of 2)
|
2004-07-05