Saturday, July 18, 2009

Episode Three: Friends with Benefits

Friendship is a special relation among classes in C++. A friend of a class is a function or class that is given access to its private (and protected) parts.



· Friendship is reflexive: An instance of a class has access to private and protected members of every other instance of the same class.

· Friendship is not symmetric: Being a friend is different from having a friend. One-way friendship is the most common situation.

· Friendship is not transitive: Friends of a class friend are not friends of the class itself.

· Friendship is not inheritable: Descendants of a class don't inherit the parent friends.

Friends break encapsulation, so it should be used wisely. Some languages offer a form of restricted friendship, in which access is granted only to certain members. Such behaviour can be emulated in C++.

One way of doing this is to declare a proxy class that implements a private interface. Such proxy class will have full access to the original class (granted either by declaring it as a nested class, or by the friend specifier), and will grant access only to the target classes of the interface.

Another alternative is by means of access keys. Access keys can be declared as:
template< typename T >
class access_key
{
friend T;

access_key() {} // default constructor is private
};
Adding an access key as an argument to a public function will prevent that function from being called in a context other than those in which an access key can be obtained. Only objects of type T can construct an access_key<T>, which grants them access to the function, but since access keys can be copied or passed by reference an object of type T can also effectively "pass friendship around".

No comments:

Post a Comment