Table of contents
1.
Introduction
2.
What is the Friend Function in C++?
2.1.
Characteristics of Friend Function
2.2.
Ways to Implement a Friend Function in C++
2.2.1.
1. Implementing the friend function Inside the class in C++ 
2.3.
C++ Code
2.3.1.
2. Implementing the friend function Outside the class in C++
2.4.
C++ Code
2.5.
C++ Code
2.6.
Example of Friend Function in C++
2.7.
C++ Code
2.8.
Features of Friend Functions in C++
2.9.
C++ Function Overloading Using Friend Function
2.10.
C++
2.11.
Advantages of Friend Functions:
2.12.
Disadvantages of Friend Functions:
3.
What is Friend Class in C++?
3.1.
Use of Friend Class in C++
3.2.
Syntax of Friend class in C++
3.3.
C++ Code
3.4.
Example of Friend Class in C++
3.5.
C++ Code
4.
Important Points About Friend Functions and Classes in C++
5.
Difference between a Friend Class and a Friend Function
6.
Frequently Asked Questions
6.1.
Differentiate between friend function and friend class?
6.2.
What is the friend class in C++?
6.3.
What is the function of a friend class?
6.4.
What is the use of friend class? 
7.
Conclusion
Last Updated: Jul 9, 2024
Easy

Friend Class and Friend Function in C++

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

Introduction

In C++, a class is a user-defined type or data structure that includes data and functions as members and whose access is controlled by the three access specifiers private, protected, and public. Access to members of a C++ class is usually restricted.

Friend Class and Friend Function in C++

A function is a code block that only executes when it is invoked. Parameters are data that may be sent into a function. Functions are used to accomplish specific tasks and are essential for code reuse: Once you've defined the code, you may use it repeatedly.

Also see, Literals in C.Fibonacci Series in C++

What is the Friend Function in C++?

When a function is defined as a buddy function in C++, it has access to the protected and private data of the class. The term friend specifies that the specified function is a friend function to the compiler. For accessing data, a friend function should be declared inside the body of a class, beginning with the term friend.

In the declaration above, the word friend is used to prefix the friend function. The function can be declared anywhere in the program, just like any other C++ function. Neither the keyword friend nor the scope resolution operator in the function declaration is utilized.

Characteristics of Friend Function

  • The friend function does not belong to the class of which it is a friend.
     
  • It can't be called with the object since it's not in the scope of that class.
     
  • It may be invoked just like any other function without the object.
     
  • It is unable to obtain member names directly. As a result, it must utilize the dot membership operator with the member name and an object name.
     
  • It might be written in a private or public area.

Ways to Implement a Friend Function in C++

There are different ways to implement the friend function in C++. 

  • Inside the class 
     
  • Outside the class



1. Implementing the friend function Inside the class in C++ 

While implementing the friend function, you can define it in the class file as well. Below is an example for better understanding. 

  • C++ Code

C++ Code

#include <iostream>

using namespace std;

class Myclass {

private:

 int value;

public:

Myclass(int data): value(data) {}

friend void display(Myclass& obj){

int value = obj.value;

cout<<"value of private data member: "<<value;

}

  

};

int main() {

 Myclass myObj(98);

display(myObj);

return 0;

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

Output

Output

2. Implementing the friend function Outside the class in C++

While implementing the friend function, you can define it outside the class file as well. Below is an example for better understanding. 

  • C++ Code

C++ Code

#include <iostream>

using namespace std;

class Myclass {

private:

 int value;

public:

 Myclass(int data): value(data) {}

friend void display(Myclass& obj);   

};

void display(Myclass& obj){

  int value = obj.value;

 cout<<"value of private data member: "<<value;

}




int main() {

Myclass myObj(76);

display(myObj);

return 0;

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

Output

Output

Program 1:
 

  • C++ Code

C++ Code

#include <iostream>	
using namespace std;
class table
{
private:
int length;
public:
table(): length(0) { }
friend int printLength(table); //friend function
};
int printLength(table b)
{
b.length += 20;
return b.length;
}
int main()
{
table x;
cout<<"Length of table: "<< printLength(x)<<endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Output

Try and compile with online c++ compiler.

Example of Friend Function in C++

  • C++ Code

C++ Code

#include <iostream>  
using namespace std;
class two; // forward declarartion.
class one
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(one,two); // friend function.
};

class two
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(one,two); // friend function
};

void min(one a, two b)
{
if(a.x<=b.y)
std::cout << a.x << std::endl;
else
std::cout << b.y << std::endl;
}

int main()
{
one a;
two b;
a.setdata(5);
b.setdata(10);
min(a,b);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Output

Features of Friend Functions in C++

  • Allow access to private and protected members of a class
  • Not members of a class but declared within its scope
  • Can be declared within a class or outside it
  • Can be declared as friend functions of multiple classes
  • Cannot access the members directly using the dot operator

C++ Function Overloading Using Friend Function

Function overloading in C++ allows multiple functions with the same name but different parameter lists. Friend functions can be overloaded to work with different classes, providing flexibility in accessing private members.

  • C++

C++

#include<iostream>
using namespace std;

class A {
int x;
public:
A() : x(0) {}
friend void display(A obj);
};

class B {
int y;
public:
B() : y(10) {}
friend void display(B obj);
};

void display(A obj) {
cout << "Value of x: " << obj.x << endl;
}

void display(B obj) {
cout << "Value of y: " << obj.y << endl;
}

int main() {
A a;
B b;
display(a);
display(b);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Value of x: 0
Value of y: 10

Advantages of Friend Functions:

  • Allows access to private and protected members of a class
  • Can be used to implement operators for user-defined types
  • Enhances encapsulation by restricting access to selected functions or classes
  • Enables efficient code reuse by allowing non-member functions to operate on class objects

Disadvantages of Friend Functions:

  • Breaks encapsulation by exposing private members to external functions
  • Can make the code less readable and harder to maintain
  • Increases coupling between classes, reducing flexibility and scalability
  • Requires careful management to ensure proper access control and minimize security risks

What is Friend Class in C++?

A friend class has access to the private and protected members of the class it is declared as a friend of. This is required when we want a specific class to have access to a class's private and protected members.

Use of Friend Class in C++

Let's understand the use of friend class in C++. 

  • Friend class in C++ helps to access the data of private members. 
  • The use of the friend class helps to write readable code. 
  • Friend class helps you in testing and debugging the errors as data of private class members are accessible. 
  • The Friend class is mostly used when operator overloading is involved in classes. To access private member data, operator overloading takes input and output, and the friend class helps in the easy access of private members. 
  • Friend classes are also used when you need to keep your interface of a class clean. 

Syntax of Friend class in C++

  • C++ Code

C++ Code

#include <iostream>  
using namespace std; 

class temp1 

   int x = 5; 
   friend class temp2; // friend class. 
}; 

class temp2 

public: 
   void display(temp1 &a) 
   { 
       cout<<"Value of x is : "<<a.x; 
   } 
}; 

int main() 

   temp1 a; 
   temp2 b; 
   b.display(a); 
   return 0; 
You can also try this code with Online C++ Compiler
Run Code

Output:

Output

Example of Friend Class in C++

  • C++ Code

C++ Code

#include <iostream>
using namespace std;

class Myclass {
private:
int privatevalue;

protected:
int protectedvalue;

public:
Myclass()
{
privatevalue = 87;
protectedvalue = 100;
}

// friend class declaration
friend class Friend_Class;
};
class Friend_Class {
public:
void show(Myclass& obj )
{
cout << "value of private data member:= "
<< obj.privatevalue << endl;
cout << "value of protected data member:= "
<< obj. protectedvalue;
}
};
int main()
{
Myclass obj;
Friend_Class friend_obj;
friend_obj.show(obj);
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Output

Important Points About Friend Functions and Classes in C++

  1. Friend Functions: Can access private and protected members of a class.
  2. Friend Classes: Entire class is granted access to private and protected members of another class.
  3. Declared Inside Class: Friend functions can be declared inside the class definition using the friend keyword.
  4. Declared Outside Class: Friend functions and classes can also be declared outside the class definition using the friend keyword.
  5. Does Not Inherit Friendship: Friendship is not inherited, i.e., a friend of a class is not necessarily a friend of its derived classes.
  6. Use with Caution: Excessive use of friend functions and classes can lead to reduced encapsulation and increased coupling.

Difference between a Friend Class and a Friend Function

Feature Friend Function Friend Class
Access Control Grants access to specific functions Grants access to all members of a class
Declaration Syntax Declared using friend keyword inside class Declared using friend keyword before class
Granularity of Access Can specify specific functions to be friends Grants access to all members of the class
Usage Suitable for granting access to individual functions Suitable for granting access to entire class

Frequently Asked Questions

Differentiate between friend function and friend class?

A friend function is generally used for accessing the non-public member of a class. A class can allow non-member functions and other classes to access its private data by making them friend. A friend class has complete access to the private data of members of another class without being a member of that class.

What is the friend class in C++?

A friend class is a special class of the main class. It has access to the private and protected members of the class it is declared as a friend of. This is required when we want a specific class to have access to a class's private and protected members.

Friend class helps to even write readable code and access the private data members of the class. 

What is the function of a friend class?

Friend class helps you to easily access the private data members' values. It further helps to maintain the encapsulation while even accessing the private data member value. It helps for easy debugging and finding the errors. 

What is the use of friend class? 

The friend class helps you to maintain the encapsulation. Friend class helps with the connectivity between the classes. The data sharing between the class with the data security is possible with the friend class. They provide enhanced code readability with easy testing and debugging. 

Conclusion

In this article, we have extensively discussed the concept of friend class and function of the C++ programming language.

We hope this blog has helped you enhance your knowledge regarding the pointers in the C language. Some official documentation on C programming language that can help you improve your understanding is C documentation.

Recommended Reading: 

Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass