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++
3.1.
C++
4.
Features of Friend Function in C++
5.
C++ friend function Example
5.1.
C++
6.
Friend Class in C++
6.1.
C++
7.
Advantages and Disadvantages of Friend Function in C++
8.
Difference Between Getter and Setter Functionality and Friend Function
9.
Frequently Asked Questions
9.1.
What is the friend function in C++?
9.2.
What is friend class with example?
9.3.
What is a function in C++ with an example?
9.4.
How to avoid breaking encapsulation while using friend functions?
10.
Conclusion
Last Updated: May 23, 2024
Medium

Friend Function in C++

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

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:

  • C++

C++

#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

Features of Friend Function in C++

  • 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.

C++ friend function Example

  • C++

C++

#include <iostream>
using namespace std;

class MyClass {
private:
int x;

public:
MyClass() : x(0) {}

friend void friendFunction(MyClass obj);
};

void friendFunction(MyClass obj) {
cout << "The value of x accessed by friend function: " << obj.x << endl;
}

int main() {
MyClass obj;
friendFunction(obj);
return 0;
}

Output:

The value of x accessed by friend function: 0

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++:

  • C++

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 of Friend Function in C++

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

AdvantagesDisadvantages
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.

Difference Between Getter and Setter Functionality and 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.

Frequently Asked Questions

What is the friend function in C++?

In C++, a friend function is a function declared within a class that has access to its private and protected members. It is not a member of the class but has the same access rights as the class's own functions.

What is friend class with example?

A friend class in C++ is a class that is granted access to the private and protected members of another class. This allows the friend class to manipulate the data of the other class as if it were its own. Here's an example:

#include <iostream>
using namespace std;

class MyClass {
private:
   int x;

public:
   MyClass() : x(0) {}

   friend class FriendClass;
};

class FriendClass {
public:
   void displayMyClassPrivateMember(MyClass obj) {
       cout << "Private member x of MyClass accessed by FriendClass: " << obj.x << endl;
   }
};

int main() {
   MyClass obj;
   FriendClass friendObj;
   friendObj.displayMyClassPrivateMember(obj);
   return 0;
}

 

What is a function in C++ with an example?

In C++, a function is a block of code that performs a specific task. It can be defined within a class (member function) or outside of a class (global function). Here's an example of a function that calculates the sum of two numbers:

#include <iostream>
using namespace std;

int add(int a, int b) {
   return a + b;
}

int main() {
   int num1 = 5, num2 = 10;
   cout << "Sum of " << num1 << " and " << num2 << " is: " << add(num1, num2) << endl;
   return 0;
}

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++. In C++, friend functions offer flexibility by allowing non-member functions to access private and protected members of a class. This feature is particularly useful for enhancing encapsulation while still enabling specific functions to interact closely with class internals. 

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