C++ Friend Functions

A class friend function is defined from outside class, but it does have access to all members of the private and protected class. With the definitions for friend functions occurring in the explanation of class, friends are not features of members.

The friend may be an attribute, a function template, or a member function, or a class or class framework, in which case friends are the entire class itself and its members.

To declare a function as a class friend, precede the function prototype with keyword friend in class definition as follows –

To declare all ClassTwo member functions as ClassOne mates, place the following declaration in the ClassOne description

Consider the following program –

Output:

C++ Friend Functions

Friend Function Special grant for access to private and protected members can be given to a friend function like friend class. Could be a friend’s function:

  • A method of another class
  •  A global function

Following are some important points regarding the functions and classes of friends:

  • Friends are only to be used for a specific time. Too many functions or external classes are clarified as friends of a class with protected or private data, decreasing the value of encapsulation in object-oriented programming of separate classes.
  • Friendship is not mutual. When Class K is a P friend, then P won’t become a P friend immediately.
  • Friendship is not hereditary (see more details here)
  • In Java, there isn’t the concept of friends.

A simple and complete C++ program to demonstrate friend Class

Output:

C++ Friend Functions

A easy and complete C++ program to explain other class friendly function

Output:

C++ Friend Functions

A simple and comprehensive C++ program to prove a global friend

Output:

C++ Friend Functions

Pin It on Pinterest

Share This