Friend function is a function, which can access the private and protected data member of a class. Using keyword friend, we can make function a friend function.
Below is the prototype for friend function
friend <return-type> function(<className>);
Example:
#include <iostream>
using namespace std;
class base {
unsigned int m_int;
public:
base() {
m_int = 20;
}
friend ostream& operator<<(ostream& s, const base& b);
};
//Source File
ostream& operator<<(ostream& s, const base& b) {
s << b.m_int ;
return s;
}
int main() {
base b;
cout << b << endl;
return 0;
}
The above example to print the object using friend operator<< function is one of the typical example of friend function.
Points to Remember
- In friend function definition, neither class name nor scope resolution operator required. This means friend function is not in the scope of a class.
- For friend function, friend keyword is required only in declaration.
- friend function is called without using object or class name.
- friend function declaration can be kept in private or public section of a class.
- friend function can access data member(private or protected) directly using dot operator as seen in the above example.