Monday, October 31, 2011

Friend Functions and Classes in C++

Some notes for friendship in C++.

  1. Friends of a class can access any member of the class, either public, protected, or private.

  2. Friends of a class can be declared as different scopes.
    1. Global functions: any object or function that is able to call the global function may get access to the class contents.
    2. Global classes: all member functions of such global class may have access to the protected and private fields of the class declaring friend.
    3. Members of other class: this will specify which member function or class of the "friend" class can have access to the class contents.

  3. Friendship is not inherited, reciprocal, or transitive.
    1. If class A is friend of B and C is derived from B, A may not be friend of C unless explicitly declared.
    2. If class A is friend of B and C is derived from A, C may not be friend of B unless explicitly declared.
    3. If class A is friend of B, B may not be friend of A unless explicitly declared.
    4. If class A is friend of B and B is friend of C, A may not be friend of C unless explicitly declared.

  4. Friends are not member of the class.
    1. The declaration of friends can be put anywhere, either public, protected, or private.
    2. The this pointer is not available in friends.

  5. A friend function or class can be the friend of multiple classes, hence they can be used for message passing between classes.

  6. 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.

  7. 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