Friend Function in C++

Video Tutorial
FREE
Functions Introduction thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate

Overview

A function can be declared as the friend of a class in C++. This function is called a friend function for that class. A friend function in C++ has the privilege to access all the private and protected data of members of the class whose friend it has been declared. These functions can be used to access the member functions of a class while still enforcing data abstraction. Classes can also be declared as a friend of another class.

What is Friend Function in C++?

In C++, global functions cannot access the private members of a class. However, sometimes we need a global function to access private members to perform certain operations, without defining it inside the class. This is where friend functions come into play.

A friend function in C++ is a non-member function that is granted access to the private, protected, and public members of a class when declared as a friend. This allows the function to perform operations that require access to private members, without having to define the function inside the class.

illustration of Friend Function in C++

Declaration of Friend Function in C++

Let us look at how we declare a function as a friend function in C++.

To declare a function as a friend function in C++, it needs to be preceded by the keyword "friend" inside the body of the class.

As you can see, the declaration of any function as a friend function in C++ is done inside the class whose data members (protected and private) are required to be accessed. The function can be defined anywhere in the code without using a scope resolution operator.

Characteristics of Friend function

Some characteristics / features of friend function in C++:

  • A global function or a member function of another class, both can be declared as a friend function.
  • A friend function in C++ should not be in the scope of the class of which it is supposed to be the friend. This means that the function which is declared as a friend should not be a member of the same class.
  • A friend function in C++ can be declared anywhere in the class, that is, in the public section or the private section of the class.
  • The friend function in C++ can be called (invoked) just like a normal function using any instance of any class (object).
  • A friend function in C++ cannot directly access the protected or private data members of the class. It is required to use an object (instance of that class) and then use the dot operator (.) to access the data members.
  • Friend functionality in C++ is not restricted to only one class. That is, it can be a friend to many classes.
  • Friend functions in C++ can use objects (instance of a class) as arguments.

Let us look at some implementations of the friend function before moving forward.

Implementing Friend Functions

As discussed above, a friend function in C++ can be either a global function or a member function of a different class. We shall look into both with an example.

A Global Function

Global Friend Function with a Class

Let us consider an example where we have a class and a global friend function for that class.

We shall create a global function and assign it as a friend function to a class in the following example.

Output

Here, in the class Travel, we have defined two private members: speed and distance. We also have a global function, findTimeofTravel(), which finds the time taken to complete a travel journey when passed an instance of the Travel class. This function needs access to the private member's distance and speed to calculate the time, but as it is outside the class Travel, we have to declare it as a friend function.

After being declared a friend, the function can easily access the private member's speed and distance and calculate the time taken for Travel.

More meaningful and standard use of the friend function in C++ would be operating on instances ( objects of classes ) of two different classes. Let us look at an example to better understand the function.

Features of Friend Functions

Some important features of friend functions in C++ are:

  • A friend function does not belong to the class for which it was designated as a friend.
  • A friend function in C++ cannot directly access the protected or private data members of the class; it is required to make use of an object (instance of that class) and then use the dot operator (.) to access the data members.
  • The friend function permits a non-member function of a class to share confidential class information.
  • The friend function enables additional functionality that is not usually utilized by the class.

C++ Function Overloading Using Friend Function

We can utilize function overloading with friend functions in C++ as well. Let us see what is function overloading.

The property of function overloading allows two or more functions in C++ to have the same names, but they should have different signatures. This means there should be a difference in those functions in terms of parameters (and)or return types. Such functions are called Overloaded Functions.

We can have two friend functions with different signatures inside a single class. Let us try to understand this better with an example.

We shall create a class and assign two functions with the same name but different signatures as friend functions to that class.

Output

The values of Coordinate c2 after changing by the second friend function are:
x: 10
y: 11

Here, in the class Coordinate, we have defined two private members: the x coordinate and the y coordinate. We also have two global functions with different signatures named change_Values(); we can see that one of them changes the values by a predefined value, whereas the other one changes it by the number passed by the user. These functions require the access of the private data members ( x and y coordinates ) to change their value, which is possible by making them a friend function to the class Coordinate. To learn more about Functions in C++, Click Here.

Advantages/Disadvantages Of Friend Functions in C++

The friend function in C++ has many advantages; let us look at some of them.

  • The friend function in C++ can provide a lot of degrees of freedom in terms of options for interface design; that is, it allows us to use different functions for other classes.
  • A friend function in C++ can be used to access all the non-public members(public access by default) of a class.
  • The friend function in C++ increases the versatility of operator overloading in C++ since functions can be overloaded as friend functions as well.
  • You can declare a member function of a class as a friend function of another class allowing access to the data of the other class.
  • Thefriend function in C++ can be used as a bridge between two classes by having it operate on the instances of both classes.
  • The friend function in C++ works symmetrically with all its friends, that is, it will work the same way with all the classes.

There are some disadvantages to it too, such as:

  • The friendship in the friend function is not transitive or reciprocal or inheritable; that is, we need to define every time that a function is a friend function when inheriting a class from another class; that is, the programmer needs to declare it as a friend function to every derived class explicitly.
  • Friend functions in C++ can not have a storage class specifier, meaning they can not be declared static or extern in the code.

Let us look at another concept similar to the friend function in C++ in the next section.

C++ Friend Class

Just like a friend function, a particular class can also have a friend class. A friend class shares the same privilege, i.e., it can access the private and protected members of the class whose friend it has been declared. This means that all the functions declared inside the friend class will also be able to access the private and protected members of the class. Before learning more about friend classes, we will first look at how to declare a class as a friend class for another class.

Syntax of Friend Class

To declare a class as a friend class in C++, it needs to be preceded by the keyword "friend" inside the body of the class, just like with the friend function.

Here friendClassName is the name of the class which is declared as the friend for the class_Name class. As you can see, this is similar to how we declare a friend function.

C++ Program To Illustrate Friend Class

Let us look at an example where another class is declared a friend of a class.

We shall create two classes Square and Shape and assign the class Shape as a friend class to the class Square.

Output

Here, we have a class Square which has a side as a private member, and the class Shape is declared as a friend of the class Square. The class Shape has a function print_area(), which calculates the area of the Square and prints it. As the Shape class is a friend class of Square, all its functions can access theprivate members of the class Square, and hence we can calculate and print the area of the Square from the Shape class.

Some Important Points About Friend Functions and Classes

  • The property of friendship in classes is not commutative. This means that if class A is a friend of class B, it does not mean that class B is also a friend of class A unless declared. So, in this case, only class A can access the private members of class B and not vice versa.
  • The property of friendship cannot be inherited. This means that if a function has been declared a friend of a parent class, it does not automatically become the friend of its child class. It becomes a friend of the child class only when it is declared as a friend in the child class also.
  • You should use friendship in moderation. This means that we should avoid declaring a lot of friend functions and classes. This is because we make classes and declare data members as private or protected to enable data hiding. If there are a lot of friend functions and classes of a class, the data isn't hidden anymore. So, extra use of friend functions defeats the purpose of object-oriented programming.

Difference between a Friend Class and a Friend Function

Some differences between a friend class and a friend function are:

Friend FunctionFriend Class
It is a function used with the keyword friend to grant a non-member function access to the private data members.It is a class used with the keyword friend to access the private data members of another class.
Forward declaration must be used in the case of Friend functions in C++.It is not necessary to use forward declaration. That is, you don't have to declare or define the class before declaring it as a friend inside another class.
Friend functions can be used to overload operators.Friend class can be used when a class is created over another class.

Conclusion

  • The friend function in C++ can be used to access the private and the protected data members of a class while not being a function of that class.
  • The friend function is declared using the keyword "friend".
  • Some characteristics of friend function are:
    • The friend function should not be in the scope of the class it is declared as a friend.
    • Friend functionality is not restricted to only one class.
    • The friend function can use objects as arguments.
    • The friend function does not directly access the data; it uses the dot operator (.) to access the data.
    • Any global or a member function of another class can be declared a friend function.
  • Some advanced uses of the friend function include:
    • Functionoverloading using friend functions.
    • Binary operator overloading using friend functions.
  • Just like the friend function, a class can also have a friend class in C++, which can access the private and protected members of the class.
  • The friend class is declared using the keywords "friend".
  • Some points to remember:
    • Friendship cannot be inherited.
    • Friendship is not commutative.
    • Use friendship in moderation.

See Also: