answersLogoWhite

0

Friends are used to extend the interface of a class. They are useful in that certain classes and functions may require private access to other class members, particularly where two classes are closely coupled (such as parent and child classes).

Friends should never be used when suitable interfaces already exist. If you have to expose an interface simply to allow an external function or class to do its job, then it would be better to declare the function or class a friend rather than expose an otherwise unnecessary interface. The key to good encapsulation is to minimise your interface as much as possible -- only expose what you absolutely must expose.

Before allowing friendship, always consider whether the function or class can be declared a member of the class itself. Static member functions are often a good choice here. However, certain functions, such as stream insertion and extraction overloads, cannot be implemented as member functions and must be implemented as external functions. These are often cited as good examples of friend functions, however keep in mind that when suitable interfaces exist, friendship is unnecessary.

Although friends are not members of the class that declares them to be a friend, they must be treated just as if they were members. That is, you must have full control over the implementation in order to maintain encapsulation. But keep in mind that the purpose of a friend is purely to gain private access for which no public interface exists and where providing such an interface would do more to undermine your encapsulation than a friend would.

User Avatar

Wiki User

11y ago

What else can I help you with?