Table of contents
1.
Introduction
2.
What is Friend Function in C++?
2.1.
Key Features of a Friend Function in C++:
3.
Declaration of Friend Function in C++
3.1.
C++
4.
Characteristics of a Friend function
5.
Global Function as Friend Function
6.
Member Function of Another Class as Friend Function
7.
C++ Friend Function Example
7.1.
C++
8.
Features of Friend Function in C++
9.
Friend Class in C++
9.1.
C++
10.
Advantages and Disadvantages of Friend Function in C++
11.
Difference Between Getter and Setter Functionality and Friend Function
12.
Frequently Asked Questions
12.1.
What is the friend function in C++?
12.2.
What is friend class with example?
12.3.
What is a function in C++ with an example?
12.4.
How to avoid breaking encapsulation while using friend functions?
13.
Conclusion
Last Updated: Jan 9, 2025
Medium

Friend Function in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello, ninjas! Welcome back to another article on C++. In this blog, we will delve into an essential concept in Object-Oriented Programming (OOP), the Friend Function in C++. Friend functions in C++ provide a mechanism to access 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 in C++.

What is Friend Function in C++?

A friend function in C++ is a function declared as a friend of a class, giving it access to that class’s private and protected members. Unlike member functions, a friend function is not part of the class but still operates on its private data.

Key Features of a Friend Function in C++:

  • Declared using the friend keyword.
  • Can access all private and protected members of a class.
  • Defined outside the class.
  • Used to improve efficiency and flexibility by avoiding excessive getter and setter functions.

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;

}
You can also try this code with Online C++ Compiler
Run Code

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 a Friend function

Some of the common characteristics of Friend function in C++ are as follows:

  • A friend function can access private and protected members of a class, but this access is granted by the class itself. This ensures that the function can interact with the class data in a controlled way.
     
  • Friend functions are commonly used to overload operators in C++. They allow operators to access private class members and perform operations that regular public member functions cannot.
     
  • Since a friend function is not a member of the class, it does not have a this pointer. This means the function is not automatically associated with an object. It needs to be provided with an object to access its members.
     
  • If a base class has a friend function, that function does not automatically have access to the private or protected members of derived classes. It needs to be explicitly declared as a friend in the derived class as well.
     
  • Since a friend function is not part of the class, it cannot be overridden in derived classes. This is different from member functions, which can be inherited and overridden.

Global Function as Friend Function

A global function can be declared as a friend of a class to allow it to access the private and protected members of that class. By declaring a global function as a friend, the class gives it special permission to interact with its internal data, even though the function is not part of the class. This allows the global function to operate on class objects directly, without needing to make the class members public. A global friend function is useful when you need to perform operations that involve multiple classes or when an external function needs access to class data in a controlled way.

#include <iostream>
using namespace std;
class Box {
private:
   int length;
public:
   Box() : length(0) {}
 
   friend void printLength(Box&);
};
void printLength(Box& b) {
   cout << "Length of the box: " << b.length << endl;
}
int main() {
   Box b;
   printLength(b); // Calling global function
   return 0;
}

Member Function of Another Class as Friend Function

A member function of another class can also be declared as a friend of a class. This means that the member function will have access to the private and protected members of the class that declared it as a friend. By doing this, classes can work together more closely, allowing one class's member functions to access another class's internal data directly. This is helpful in cases where two classes need to collaborate but one class wants to keep its data private, ensuring that only trusted functions (like specific member functions of another class) can access it.

#include <iostream>
using namespace std;
class Box {
private:
   int length;
public:
   Box() : length(5) {}
   
   friend class BoxPrinter;
};
class BoxPrinter {
public:
   
   void printLength(Box& b) {
       cout << "Length of the box: " << b.length << endl;
   }
};
int main() {
   Box b;
   BoxPrinter printer;
   printer.printLength(b); // Calling the friend member function
   return 0;
}

C++ Friend Function Example

Friend Function in C++ can be understood better using an example given below:

  • 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;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

The value of x accessed by friend function: 0

Features of Friend Function in C++

Some of the common features of C++ Friend Function are as follows:

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

Friend Class in C++

The essential characteristics of C++ Friend Class 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;

}
You can also try this code with Online C++ Compiler
Run Code

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 in C++. 

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

C++ 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?

C++ Friend Class 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

Live masterclass