Explain 'FRIEND CLASS' .
or
Define 'FRIEND CLASS ' with program.
A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class. This requires the condition that the friend becoming class must be first declared or defined (forward declaration).
EXAMPLE:
#include <iostream.h>
#include<conio.h>
class sample_1
{
friend class sample_2;//declaring friend class int a,b;
public:
void getdata_1()
{
cout<<"Enter A & B values in class sample_1"; cin>>a>>b; }
void display_1()
{
cout<<"A="<<a<<endl; cout<<"B="<<b<<endl;
}
};
class sample_2
{
public: int c,d,sum; sample_1 obj1;
void getdata_2()
{
obj1.getdata_1();
cout<<"Enter C & D values in class sample_2";
cin>>c>>d; } void sum_2()
{
sum=obj1.a+obj1.b+c+d;
}
void display_2()
{
cout<<"A="<<obj1.a<<endl; cout<<"B="<<obj1.b<<endl; cout<<"C="<<c<<endl; cout<<"D="<<d<<endl; cout<<"SUM="<<sum<<endl;
}
};
int main()
{
clrscr();
sample_1 s1; s1.getdata_1(); s1.display_1();
sample_2 s2;
s2.getdata_2();
s2.sum_2();
s2.display_2();
}
getch();
return 0;
}
Output
Enter A & B values in class sample_1:1 2
A=1
B=2
Enter A & B values in class sample_1:1 2 3 4
Enter C & D values in class sample_2:A=1
B=2
C=3
D=4
SUM=10.
HOPE THIS INFORMATION IS BENEFICIAL TO YOU.