Some notes for friendship in C++.
- Friends of a class can access any member of the class, either public, protected, or private.
- Friends of a class can be declared as different scopes.
- Global functions: any object or function that is able to call the global function may get access to the class contents.
- Global classes: all member functions of such global class may have access to the protected and private fields of the class declaring friend.
- Members of other class: this will specify which member function or class of the "friend" class can have access to the class contents.
- Friendship is not inherited, reciprocal, or transitive.
- If class A is friend of B and C is derived from B, A may not be friend of C unless explicitly declared.
- If class A is friend of B and C is derived from A, C may not be friend of B unless explicitly declared.
- If class A is friend of B, B may not be friend of A unless explicitly declared.
- If class A is friend of B and B is friend of C, A may not be friend of C unless explicitly declared.
- Friends are not member of the class.
- The declaration of friends can be put anywhere, either public, protected, or private.
- The this pointer is not available in friends.
- A friend function or class can be the friend of multiple classes, hence they can be used for message passing between classes.
- The definition of friends can be placed in the body of class who declares the friendship. Even in this case, the friend functions or classes are in the global scope, not members of the class.
- Do friends violate encapsulation?
No! If they're used properly, they enhance encapsulation. Many people think of a friend function as something outside the class. Instead, try thinking of a friend function as part of the class's public interface. A friend function in the class declaration doesn't violate encapsulation any more than a public member function violates encapsulation: both have exactly the same authority with respect to accessing the class's non-public parts.
References:
Coding Unit Tutorials
C++ FAQ
No comments:
Post a Comment