|
||
|
Lesson 4
Objective
|
Friend functions
How and where to declare a friend function. |
|
|
Before continuing our exploration of operator overloading, we need to master the use of friend functions.
A friend function gives a nonmember function access to the hidden members of the class and must be declared inside the class declaration to which it is a friend. The function is prefaced by the keyword friend and can appear in any part of the class without affecting its meaning. Our style in this course is to place the friend declaration in the public part of the class. Since access has no effect on the friend declaration, friend functions are conceptually public. Member functions of one class can be friend functions of another class. In this case, they are declared in the class to which they are a friend, using the scope resolution operator to qualify its function name. If all member functions of one class are friend functions of a second class, this can be specified by using the general form: friend class class name. The following declarations illustrate this syntax:
class window {
.....
friend void refresh(window w); //friend
friend void terminal::draw(window w); //friend
};
class node {
.....
friend class tree;
//tree members have access to node
};
Click the Quiz button to take a brief multiple-choice quiz on friend functions.
Friend Function - Quiz |
||
|
|
||