Friend Functions and Friend Classes in C++

Friend Functions and Friend Classes in C++

You must have heard about encapsulation and how C++ allows friend functions or friend classes to access private data in C++ programs. The friend function in C++ is frequently misused, or there is a lack of understanding about when to use a friend class instead of a normal member function. This article will cover the secrets of declaring friend functions, function overloading, accessing private and protected members, the difference between friend functions and friend classes, and how to access private members in C++.

Table of Contents:

What Is a Friend Function in C++?

The friend function in C++ is a function that is not a member of a class, but it allows you to access private members in C++, as well as protected members. These members are accessed only within the class. By using a friend function, we can easily access the external functions. We use the friend keyword inside a class definition to declare a friend function in C++.  

A friend can be declared a function, a function template, a member function, or a class template.

How to Declare a Friend Function in C++

By using the keyword friend, we declare a friend function inside a class. This function does not belong to the class, but it has permission to access private members in C++. It is defined outside the class, like a normal function.  

Example 1: Using a Friend Function in C++ to Access Private Data

This example directly shows the use of friend functions in C++ to access private members.

Cpp

Output:

Using a Friend Function to Access Private Data

The above program uses a friend function to access private members in C++. Here, the friend function is declared inside the class, but it was defined outside the class. In the main function, an object is created, s1, and showData(s1) is used to print the private data.

Example 2: Add Members of Two Different Classes

The friend function in C++ program is used to access private members and manipulate the data from multiple classes.  This is the other practical example that explains the use of friend functions in C++.

Cpp

Output: 

Add Members of Two Different Classes

To access the private members in C++ of ClassA and ClassB, the program uses the friend function. The add() function sums their private data by declaring them as friends in both classes.

Function Overloading in C++ using Friend Function

Function overloading in C++ allows multiple functions with the same name but different parameters. Based on the different argument types or counts, friend functions can be overloaded. 

Example 3: Overloading a Friend Function in C++

Cpp

Output:

C++ Function Overloading using Friend Function

The above program does function overloading in C++ with a friend function. The Example class has a private member that is a value; it is accessed by using two overloaded display functions that are declared as friends. It prints the value with the first version and the string message with the second version.

Key Characteristics of C++ Friend Functions

  1. Access to Private Members – Friend functions help you to access private members in C++ and protected data of a class.
  2. Declared Inside, Defined Outside – Declared as a friend of the class but defined outside.
  3. Not a Member Function – It is not called by an object of the class.
  4. Can Be Overloaded – Friend functions may be overloaded like regular functions, showcasing the flexibility of function overloading in C++.
  5. Used for Overloading Operators  – You can use friend functions while overloading those operators that require access to private data. This is an important use of friend functions in C++ and specifically refers to operator overloading with friend function.
  6. Breaks Strict Encapsulation - It breaks encapsulation a bit as it allows you to access private members in C++.

Practical Applications of Friend Functions in C++

The practical applications given below directly show the use of friend functions in C++:

  • Accessing Private Members – Permit external functions to gain access to private members in C++ and protected data.
  • Operator Overloading with Friend Function - A Friend function in C++ is used to overload the operators like +, -, *, etc., to access private members in C++.
  • Multiple Class Interaction – Function can access the private data of multiple classes (e.g., adding the object of various classes).
  • Implementing Friend Class – A friend class in C++ is required when a whole class needs to access private members in C++ of another class.
  • Flexibility in Encapsulation – Allows you to control the access to private members in C++ without exposing them to the world.
  • Interfacing With Non-Member Functions – Handy for dealing with some non-member functions, but not wanting to make it a member function.

What Is a Friend Class in C++?

The friend class in C++ is a class that gives access to the private and protected members of another class. Friend class is similar to the friend functions, except that it grants the permission to individual functions. This is helpful when multiple classes need to work closely together, share data, or have a high degree of interaction while still maintaining some level of encapsulation and data hiding.

How to Declare a Friend Class in C++

By using the keyword friend, a class can declare another class as its friend. This means all the private and protected members of the class are accessible to the friend class in C++. 

Accessing Private and Protected Members

If we declared the class as a friend, then all the member functions of the class can directly access private members in C++ and the protected data of another class. 

C++ Friend Class Example:

Cpp

Output:

C++ Friend Class

The following C++ program demonstrates the friend class. The Sample class has a private member secret, which is not accessible outside of the class. But now Helper is a friend class, and all the functions of Helper, including showData(), can access the private members of the Sample. The showData() function prints the secret value of a Sample object. So in main(), we create the object s1 and pass 50 to its constructor. Note that h.showData(s1) will print the private data.

Friend Class vs Friend Function in C++ – Key Differences

Here is a comparison table that shows the difference between friend function and friend class in C++:

Friend Function in C++ Friend Class in C++
Access Level Only the specific function is granted access All functions of the friend class get access
Scope Defined outside the class, but can access private/protected members The whole class gets access to another class’s private/protected members
Use Case Used for specific operations, like arithmetic functions or comparisons Used when two classes need to share internal details, like a helper or utility class
Security More restrictive (only one function gets access) Less restrictive (entire class gets access)

When Should You Use a Friend Function in C++?

The points given below explain the use of friend functions in C++:

  • Use a friend function in C++ when you need to allow an external function to access private members in C++ or protected members.
  • It is useful when two or more classes need to work closely together and access each other’s internals.
  • You can also perform operator overloading with friend function(like operator<< or operator==) when the left-hand operand isn’t a class object.
  • You should use it when encapsulation would otherwise force you to write inefficient or complex accessor methods.
  • They are appropriate when the function logically doesn’t belong to the class but still needs internal access.
  • Use the friend function in C++ with caution, as it breaks encapsulation, and tight coupling can make code harder to maintain.
  • Avoid using friend functions if the same functionality can be achieved through proper public interfaces or inheritance.

Best Practices for Using Friend Classes in C++

  • Use a friend class in C++ only when two classes need to share private data closely.
  • Avoid using friend classes too often, as it can break the idea of data hiding.
  • Make specific classes as the friend class in C++ rather than many, to keep control tight.
  • Always explain in comments why a class needs to be a friend for clarity.
  • Try to avoid mutual friendship between classes to prevent tight coupling.
  • Prefer public methods or design changes before choosing friendship.
  • Place the friend declaration near the members it needs to access.
  • Use friend classes mainly for internal tasks like debugging or serialization.

Conclusion

In C++, friend functions and friend classes allow you to access private and protected members of a class without breaking encapsulation completely. Operator overloading with friend function, multiple class interaction, and methods to access private members in C++ for these friend functions are beneficial for all of them, as they do not need to be members of the class. Although friend functions and classes enhance flexibility, they also reduce strict encapsulation, so they should be used with caution. Generally, they are strong supporting actors that govern the interactions of classes of objects and tend to a balance between security and utility.

You can learn more about C++ in the C++ article, and also explore C++ Interview Questions prepared by industry experts.

Friend Functions in C++ – FAQs

Q1. What is a friend function in C++?

Friend function is a function that is not a member of a class, but it allows access to its private and protected members.

Q2. How do you declare a friend function?

Use the keyword friend to declare a friend function inside a class.

Q3. What is the difference between a friend function and a friend class?

A friend function allows one function to access the private member, whereas a friend class allows all its functions to access them.

Q4. Can a friend function be overloaded in C++?

Yes, by using different parameter lists, a friend function can be overloaded.

Q5. Why use a friend class in C++?

The friend class is a class that gives access to the private and protected members of another class.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.