Friend Function
If a function is defined as a friend function then, the private and protected data of a class can be accessed using the function. The compiler
knows a given function is a friend function by the use of the keyword friend. For accessing the data, the declaration of a friend
function should be made inside the body of the class ( can be anywhere inside class either in private or public section) starting with keyword friend.
Syntax:
class classname
{
friend return_type function_name(argument/s)
};
return_type function_name(argument/s)
{
// private and protected data of classname can be accessed from
// this function because it is a friend function of classname
};
#include< iostream.h >
class box
{
public: //access specifier
int height; // data member
int width;
int area;
box() // memeber function
{
height=10;
width=5;
}
friend void area(box);
};
void area(box a)
{
a.area = a.height*a.width;
cout<<"Area of box = " << a.area;
}
void main()
{
box box1; // createing object
area(box1);
}
Output:
Friend class
A friend class is a class that can access the private and protected members of a class in which it is declared as friend. This is needed when
we want to allow a particular class to access the private and protected members of a class.
#include< iostream.h >
class demo1
{
int a=5;
friend class demo2;
};
class demo2
{
public:
void show(demo1 &b)
{
cout<<"value of a is : " << b.a;
}
};
void main()
{
demo1 obj1; // createing object
demo1 obj2;
obj2.show(obj1);
}
Output: