Friend Function:-
1:-------------------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;
class Ankit;
class Ankush
private:
int money=10;
friend void rohit(Ankit,Ankush);
};
class Ankit
private:
int money=20;
friend void rohit(Ankit,Ankush);
};
void rohit(Ankit r1, Ankush r2)
cout<<"Sum"<<r1.money+r2.money;
int main ()
Ankush obj1;
Ankit obj2;
rohit (obj2,obj1);
return 0;
o/p:-
2:--------------------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;
class ABC;
class XYZ {
int x;
public:
void get(int i) {
x = i;
friend void sum(XYZ, ABC);
};
class ABC {
int y;
public:
void get(int j) {
y = j;
friend void sum(XYZ, ABC);
};
void sum(XYZ m, ABC n) {
cout << "Sum of values = " << (m.x + n.y) << endl;
int main() {
ABC abc;
abc.get(10);
XYZ xyz;
xyz.get(20);
sum(xyz, abc);
return 0;
O/P:-
3:--------------------------------------------------------------------------------------------------------
Let's see the simple example of C++ friend function used to print the length of a box.
#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;
O/P:-
4:--------------------------------------------------------------------------------------------------------
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;
O/P:-
In the above example, min() function is friendly to two classes, i.e., the min()
function can access the private members of both the classes A and B.
5:--------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class Distance {
private:
int i;
public:
Distance() {
i = 0;
friend int add_two(Distance);
};
int add_two(Distance d) {
d.i = d.i + 2;
return d.i;
int main() {
Distance d1;
cout << add_two(d1);
return 0;
o/p:-
6:------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class sample {
int a, b;
public:
void get_data(int i, int j) {
a = i;
b = j;
friend float avg(sample s);
};
float avg(sample s) {
return float(s.a + s.b) / 2.0;
int main() {
sample s;
s.get_data(5, 6);
cout << "\navg is " << avg(s);
return 0;
O/P:-