The private data members of a class cannot be accessed by functions that are not a part of the class. The access to such members can only be given to the functions by specifying the function as friend of the class whose data structures are required by the function. In simple words, we can say that a friend function has an advantage of having an access to the private data members of the friend class.

A function can be specified as a friend of a class by including its prototype in the class preceded by the keyword friend.

For example, the function xyz can be made friend to a class called test as shown below:

It should be noted that the function xyz() has been defined as an ordinary function outside its friend class called test. However, it can read or write the data members of the class test. This feature of C++ is helpful in a situation where the programmer desires to access the data members of two different objects of the same class or two different classes. Since a friend function violates the encapsulation property of its friend class, the large scale usage of friend will degrade the overall object oriented concept.

A friend function possesses certain special characteristics:

  • The friend function is not in the scope of the class, to which it has been declared as a friend.
  • Since it is not in the scope of the class, it cannot be called using the object of that class.
  • It can be invoked like a normal function without the help of any object.
  • Unlike the member functions, it cannot access the member names directly and has to use an object name followed by a dot(.) operator with each member name.
  • It can be declared in public or private section, within the class, without affecting its meaning

The programmer should follow some guidelines in the usage of a friend function:

  • Do not use friend functions very often. Use such a function only when required.
  • A friend function may be allowed for operations related to public interface of the class.
  • The friend function should not be allowed outside the team working on the project.

Program illustrating use of a friend function as an interface between two classes