What do you mean by friend class and friend function?

Friend function and friend classes.
Private member of a class can not be accessed from outside the class. Non member function of a class cannot access the member of class. Using friend function we can achieve this. A fried function also acts as a bridging between two class. It can operate the object of two classes.
 Friend function is declared inside the class any where in private or public section with keyword friend.
 Friend function are defined outside the class as a normal function.
An example: Friend function operating objects of two classes.
#include<iostream.h>
class beta ;
class alpha
{
private:
int data ;
public:
alpha() { data=10;}
friend int frifunc(alpha ,beta);
};
class beta
{ private:
int data;
public:
beta() { data = 20; }
friend int frifunc(alpha, beta);
};
int frifunc(alpha a, beta b)
{ return (a.data + b.data);
}
void main ( )
{
alpha aa;
beta bb;
cout<<frifunc(aa, bb)<<endl;
}
output: 30
Friend class:
When a class is to be made friend to another class, we should declare that class as friend inside another. as
class A class B
{ // body of A { // Body of B
friend class B;
}; };
Here class B is friend class to A.
 When a class is declared as friend within another class entire function of friend class can access the private data of the class to which it becomes friend.
 Here in above example, all member function of B can access private data of class A.
Another way of declaration
class B;
class A
{
// Body of class A
friend B;
};
class B
{
// Body
};
//An Example:
#include<iostream.h>
class A
{
private:
int data;
public:
A(){data = 100;}
friend class B;
};
class B
{
public:
void func1(A a)
{cout<<"\ndata= "<<a.data;}
void func2(A b)
{
cout<<"\ndata = "<<b.data<<endl;
}
};
void main()
{
A a;
B b;
b.func1(a);
b.func2(a);
}
The output: data= 100
data = 100

0 comments:

Feel free to contact the admin for any suggestions and help.