Friend functions
In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affectfriends.Friends are functions or classes declared with the
friend
keyword.If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
24 |
The duplicate function is a friend of CRectangle. From within that function we have been able to access the memberswidth and height of different objects of type CRectangle, which are private members. Notice that neither in the declaration ofduplicate() nor in its later use in main() have we considered duplicate a member of class CRectangle. It isn't! It simply has access to its private and protected members without being a member.
The friend functions can serve, for example, to conduct operations between two different classes. Generally, the use of friend functions is out of an object-oriented programming methodology, so whenever possible it is better to use members of the same class to perform operations with them. Such as in the previous example, it would have been shorter to integrateduplicate() within the class CRectangle.
Friend classes
Just as we have the possibility to define a friend function, we can also define a class as friend of another one, granting that first class access to the protected and private members of the second one.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
16 |
In this example, we have declared CRectangle as a friend of CSquare so thatCRectangle member functions could have access to the protected and private members ofCSquare, more concretely to CSquare::side, which describes the side width of the square.
You may also see something new at the beginning of the program: an empty declaration of classCSquare. This is necessary because within the declaration of CRectangle we refer to CSquare (as a parameter inconvert()). The definition of CSquare is included later, so if we did not include a previous empty declaration forCSquare this class would not be visible from within the definition of CRectangle.
Consider that friendships are not corresponded if we do not explicitly specify so. In our example,CRectangle is considered as a friend class by CSquare, but CRectangle does not consider CSquare to be a friend, so CRectangle can access the protected and private members ofCSquare but not the reverse way. Of course, we could have declared also CSquare as friend of CRectangle if we wanted to.
Another property of friendships is that they are not transitive: The friend of a friend is not considered to be a friend unless explicitly specified.