The friend
function in object-oriented programming (OOP) can access all the public, private, and protected members of a class. It is a non-member function of a class. We use the friend
reserved word to make a friend
function.
Note: We can learn more about the
friend
function here.
The syntax of the friend
function is as follows:
class A{friend data_type funtion_name (parameters);};data_type function_name (parameters){}
We can declare the function anywhere in the class.
Note: There is no
friend
function in Java.
Let’s declare all the classes we want to use in the friend
function beforehand. The required code is as follows:
#include<iostream>using namespace std;class B;class A{int a1 = 9;public:friend int add(A, B);};class B{int b1 = 10;public:friend int add(A, B);};int add(A a, B b){return a.a1 + b.b1;}int main(){A object1; // Object of class AB object2; // Object of class Bcout << add(object1, object2);return 0;}
class B
. (This is a good approach to declare all classes and functions before defining them).a1
in class A
. We initiate it with a value of 9.friend
function by using the friend
reserved word. b1
in class B
. We initiate it with a value of 10.add
is defined here. We define the friend
function like any other function, except for one difference. Unlike with other data types of the parameter, we name the classes where we declare the `friend` function.class A
named object1
.class B
named object2
.friend
function and pass both the objects as parameters. Meanwhile, the cout
statement displays the answer on the screen.friend
function, we lose the purpose of the encapsulation.friend
function outside the class.friend
function can use any class member we declare it in.