Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Friend Function in C++?
3.
Declaration of Friend Function in C++
4.
Characteristics of Friend Function
5.
The Function is Friendly to two Classes.
6.
Friend Class in C++
7.
Advantages and Disadvantages 
8.
Explain How the Getter and Setters Functionality Differs from a Friend Function
9.
Frequently Asked Questions
9.1.
Can a friend function access static members of a class?
9.2.
Can a friend function be a member function of another class?
9.3.
How to avoid breaking encapsulation while using friend functions?
10.
Conclusion
Last Updated: Mar 27, 2024
Medium

Friend Function in C++

Introduction

Hello, ninjas! Welcome back to another article on C++. In this blog, we will look at another exciting topic of C++, which is Friend Functions. Friend function in C++ is essential because they provide a mechanism for accessing private and protected members of a class without violating encapsulation. 

Friend Function in CPP

After this blog, the reader will have a strong hold over the concepts and workings of Friend Functions.

Fibonacci Series in C++

What is Friend Function in C++?

A friend function in C++ is declared a friend of a class and has access to its private and protected members. It is a function that can access a class's private data members and member functions without being a member.

Friend functions are defined inside or outside the class definition and declared with the keyword 'friend.' A function can access all the private and protected members of the class after being declared its friend.

The primary use of friend functions is to provide external functions that can work on the private data of a class without breaking its encapsulation. It allows for more efficient and flexible programming. It will enable functions to operate on private data without needing getter and setter functions or publicizing all members.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Declaration of Friend Function in C++

The friend function in C++ can be declared as follows:

#include <iostream>

using namespace std;

class MyClass {

    private:

        int x;

    public:

        MyClass() {x = 0;}

        void setX(int val) { x = val; }

        friend void myFriendFunction(MyClass obj); // declaration of friend function

};

void myFriendFunction(MyClass obj) {

    cout << "Value of private member x is: " << obj.x << endl;

}

int main() {

    MyClass obj;

    obj.setX(10);

    myFriendFunction(obj); // calling the friend function

    return 0;

}

This example shows a class MyClass with two private data members, x and y. We also have a friend function, "add," declared inside the class, which has access to the private data members of MyClass.

We declare the friend function with the friend keyword inside the class definition and define it outside it. When we call add in the "main" function, we pass an object of MyClass as an argument, and the function can access the private data members x and y of that object using the dot operator.

Output:

The sum of x and y is 30.
 
Output

Characteristics of Friend Function

  • A friend function is a unique function that can access private and protected members of a class.
     
  • Friend functions can be declared inside or outside the class definition using the friend keyword.
     
  • Friend functions are not class members and do not have this pointer.
     
  • Friend functions help provide external functions that can work with private data members of a class without breaking encapsulation.
     
  • Using friend functions can improve the efficiency and flexibility of code by avoiding the need to make all members public or to use getter and setter functions.
     
  • Friend functions cannot access static members of a class.
     
  • A friend function in C++ is a non-member function that has access to private and protected members of a class. When used with the "this" keyword, it can access the member variables and functions of the class as if it were a member function.
     

The Function is Friendly to two Classes.

For example, consider the code:

#include <iostream>

using namespace std;

class ClassB; // forward declaration of ClassB

class ClassA 

{

    private:

        int x;

    public:

        ClassA(int a) {

            x = a;

        }

        friend int add(ClassA objA, ClassB objB); // declaration of friend function

};

class ClassB 

{

    private:

        int y;

    public:

        ClassB(int b) {

            y = b;

        }

        friend int add(ClassA objA, ClassB objB); // declaration of friend function

};

int add(ClassA objA, ClassB objB) 

{

    int sum = objA.x + objB.y;

    return sum;

}

int main() {

    ClassA objA(50);

    ClassB objB(60);

    int result = add(objA, objB); // calling the friend function

    cout << "The sum of x and y is: " << result << endl;

    return 0;

}

In this example, we have classes, ClassA and ClassB, each with private data members. Using a friend function, we want to add the private data members x of ClassA and y of ClassB.

To do this, we declare the friend function add inside both classes and pass objects of both classes as arguments to the function. Since the add function is a friend function of both classes, it has access to their private data members.

In the add function, we add the private data members x and y of the ClassA and ClassB objects, respectively, and return the result.

In the main function, we create objects of both classes and pass them as arguments to the add function. We then print the result to the console.

Output:

The sum of x and y is 110
Output

Friend Class in C++

The essential characteristics of Friend classes are as follows:

  • In addition to friend functions, C++ allows friend classes, which access a class's private and protected members.
     
  • A friend class is declared using the friend keyword followed by the class name, either inside or outside the class definition.
     
  • Like friend functions, friend classes can provide external access to private members of a class without breaking encapsulation.
     
  • Friend classes can access all members, including private and protected members, without needing getter and setter functions.
     
  • Friend classes are used to implement complex algorithms or data structures that require access to private members of a class while still maintaining the integrity of the class's interface.
     
  • Unlike friend functions, friend classes are members of the class and have access to this pointer, which allows them to access members of the current object.

Here's an example of how to declare and use a friend class in C++:

#include <iostream>

using namespace std;

class MyClass 

{

private:

    int x;

public:

    MyClass(int a) 

    {

        x = a;

    }

   friend class MyFriendClass; // declaration of friend class

};

class MyFriendClass {

public:

    void printX(MyClass obj) {

        cout << "The value of x is: " << obj.x << endl;

    }

};

int main() {

    MyClass obj(10);

    MyFriendClass friendObj;

    friendObj.printX(obj); // calling friend class function

    return 0;

}

This example shows a class MyClass with a private data member x. We want to allow access to the private member x by a friend class, MyFriendClass.

To do this, we declare MyFriendClass as a friend class of MyClass using the friend keyword inside the class definition of MyClass.

In MyFriendClass, we define a function printX that takes an object of MyClass as an argument and prints the value of its private data member x.

In main, we create an object of MyClass and an object of MyFriendClass and call the printX function on the object of MyFriendClass, passing in the object of MyClass as an argument.

The output would be:

The value of x is 10
Output

Advantages and Disadvantages 

Let us learn and discuss the advantages and disadvantages of using friend functions. 

Advantages Disadvantages
Selective access to private and protected members. Violates the principle of encapsulation.
Simplifies complex algorithms and data structures. Increases code coupling.
Improves performance by reducing function calls and data copying. It can make access control more difficult.
Enhances code readability and organization. It can make code harder to understand.
Simplifies testing and debugging. Increases the risk of errors and bugs.

Explain How the Getter and Setters Functionality Differs from a Friend Function

Below we have discuss how getter and setters functionality differs from a friend function function: 

 Getter/Setter Function   Friend Function
It accesses and modifies data. It accesses private data.
Access control is public. Accessible by class's friends and members.
The scope of access is only to specific data members. Access to All private and protected data members of the class.
Class dependency is high. Class dependency is low.

Also check out this article - Pair in C++

Frequently Asked Questions

Can a friend function access static members of a class?

Yes, a friend function can access static members of a class.

Can a friend function be a member function of another class?

Yes, a friend function can be a member function of another class. The friend function must be declared a friend of the class it needs to access.

How to avoid breaking encapsulation while using friend functions?

To avoid breaking encapsulation while using friend functions, one can make the function a member of a separate class that can access the target class or uses the "friend-of-a-friend" principle, where a class that has access to another class's private members can act as an intermediary for the friend function.

Conclusion

The article discussed various aspects of the Friend Function in C++. We hope this blog has helped you enhance your knowledge regarding Friend Function in C++.

You may also refer

Useful C++ Libraries.

C++ Projects for Beginners

Stoi In C++

Bubble Sort Program in C

C++ Interview Questions

You may refer to our Guided Path on Code Studios to enhance your skill set on DSA and many more. Check out essential interview questions, practice our available mock tests, and more!

Happy Reading!

Live masterclass