In C++, a function or an entire class can be declared a friend of another class or function. This tutorial will teach you how to use the friend function in C++.
A standard function, not a member function of a class, has no privilege to access private
data members, but a friend function can access any private
data members. A friend function can also be used for function overloading.
A Friend function declaration can be specified anywhere in the class. But it is good practice to define it where the class ends. Declaring the friend function is straightforward. The keyword friend
comes before the class prototype inside the class definition.
Syntax:
class className {
...
friend returnType functionName(arguments);
...
}
Example to Demonstrate the Working of the Friend Function
Example:
/* C++ program to demonstrate the working of friend function.*/
#include <iostream>
using namespace std;
class Distance {
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d){
//function definition
d.meter=10; //accessing private data from non-member function
return d.meter;
}
int main(){
Distance D;
cout<<"Distace: "<<func(D);
system("pause");
return 0;
}
Program Output:
Here, the friend function func()
is declared inside the Distance class. So, private data can be accessed from this function. However, this example gives you what idea about the concept of friend function.
In C++, friend means to permit a class or function. The non-member function has to grant access to update or access the class.
The advantage of encapsulation and data hiding is that a non-member function of the class cannot access the member data of that class. Care must be taken using the friend function because it breaks the natural encapsulation, which is one of the advantages of object-oriented programming. It is best used in operator overloading.