In C++, if a function is declared as a friend function, the function can access a class’s protected and private data.
The keyword friend informs the compiler that the supplied function is a friend function.
The declaration of a friend function should be done inside the body of a class commencing with the keyword friend for accessing the data.
In C++, the friend function is declared:
class class_name
{
// syntax of friend function.
friend data_type function_name(argument/s);
};
The friend function is started by the term friend in the above declaration. Like any other C++ function, the function can be declared anywhere in the program.
Neither the keyword friend nor the scope resolution operator is used in the function declaration.
Characteristics of a Friend function:
- The function is not in the scope of the class to which it is a friend.
- It can’t be called with the object since it’s not in that class’s scope.
- It may be called like any other function without the need for the object.
- It can’t directly access member names, therefore it must use an object name and the dot membership operator with the member name.
- It might be stated in either the private or public section.
Example of a friend function in C++:
#include <iostream> using namespace std; class Box { private: int length; public: Box(): length(0) { } friend int printLength(Box); //friend function }; int printLength(Box b) { b.length += 10; return b.length; } int main() { Box b; cout<<"Length of box: "<< printLength(b)<<endl; return 0; }
Output:
Length of box: 10
Let’s see a simple example when the function is friendly to two classes:
#include <iostream> using namespace std; class B; // forward declarartion. class A { int x; public: void setdata(int i) { x=i; } friend void min(A,B); // friend function. }; class B { int y; public: void setdata(int i) { y=i; } friend void min(A,B); // friend function }; void min(A a,B b) { if(a.x<=b.y) std::cout << a.x << std::endl; else std::cout << b.y << std::endl; } int main() { A a; B b; a.setdata(10); b.setdata(20); min(a,b); return 0; }
Output:
10
The min() method in the above example is friendly to two classes, i.e., it may access the private members of both classes A and B.
The Friend class In C++:
A friend class has access to both private and protected members of the class it is defined as a friend in.
Let’s see a simple example of a friend class:
#include <iostream> using namespace std; class A { int x =5; friend class B; // friend class. }; class B { public: void display(A &a) { cout<<"value of x is : "<<a.x; } }; int main() { A a; B b; b.display(a); return 0; }
Output:
value of x is : 5
Class B is defined as a friend inside class A in the example above. As a result, B is a class A friend. Class B has access to class A’s private members.