What is a Friend Function?
- The friend function is a special function in C++ that in spite of not being a member function of a class has the privilege to access private and protected data of a class.
- It is a non-member function or ordinary function of a class, which is declared as a friend using the “friend” keyword inside the class. By declaring a function as a friend, all the access permissions are given to the function.
- The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition.
- When the friend function is called neither name of the object nor the dot operator is used. However, it may accept the object as an argument whose value it wants to access.
- A friend function can be declared in any section of the class i.e. public/private/protected.
Declaration of Friend Function in C++
Syntax:
class<class_name> { friend<return_type><function_name>(argument); };
Code:
C++ Code
// Code to swap two numbers using the friend function.
#include<iostream>
using namespace std;
class Swapping {
int a, b;
public:
void set_data();
friend void swap_no(Swapping & s);
void display();
}s1;
void Swapping::set_data() {
cout << "Enter two numbers to be swapped: ";
cin >> a >> b;
}
void swap_no(Swapping & s) {
int temp = s.a;
s.a = s.b;
s.b = temp;
}
void Swapping::display() {
cout << a << " , " << b << endl;
}
int main() {
s1.set_data();
cout << "Before swap: ";
s1.display();
swap_no(s1);
cout << "After swap: ";
s1.display();
return 0;
}
Output:
Enter two numbers to be swapped: 5 4
Before swap: 5, 4
After swap: 4, 5
What is a Friend Class?
A friend class can access both private and protected members of the class in which it has been declared as a friend.
Code:
C++ Code
// Code for demo of friend class in C++.
// In this example, class B is declared as a friend inside class A.
// Therefore, B is a friend of class A and hence class B can access
// the private members of class A.
#include<iostream>
using namespace std;
class A {
int x;
public:
A() {
x = 10;
}
friend class B; //friend class
};
class B {
public:
void display(A & t) {
cout << endl << "The value of x = " << t.x;
}
};
int main() {
A _a;
B _b;
_b.display(_a);
return 0;
}
Output:
The value of x = 10
Special thanks to Aakriti Singh for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article