Explain 'FRIEND' function or describe 'FRIEND' function.
A friend function is a function which is declared within a class and is defined outside the class. It does not require any scope resolution operator for defining . It can access private members of a class. It is declared by using keyword “friend”.
The private members cannot be accessed from outside the class. i.e.… a non member function cannot have an access to the private data of a class. In C++ a non member function can access private by making the function friendly to a class.
Example:-
class sample
{
int x,y;
public: sample(int a, b);
friend int sum(sample s);
};
sample::(int a,b)
{
x=a; y=b;
}
int sum(sample s)
{
int sum;
sum= s.x + s.y;
return 0;
}
void main()
{
Sample obj(2.3);
int res= sum(obj);
cout<<"sum0="<<res<<endl;
}
A friend function possesses certain special characteristics:
i) It is not in the scope of the class to which it has been declared as 'friend'. Since it is not in the scope of the class , it cannot be called using the object of that class. It can be invoke like a normal function without the help of any object.
ii) Unlike member function , it cannot access member names directly and has to use an object name and dot membership operator with each member name.
iii) It can be declared either in the public or private of a class without affecting its meaning.
iv) Usually , it has the objects are arguments.
Write a program to find max of two number using 'friend' function.
#include<iostream.h>
#include <conio.h>
class sample2; class sample 1
{
int x;
public: sample(int a);
friend void max(sample s1, sample s2)
};
sample 1:: sample(int a)
{
x=a;
}
class sample2
{
int y; public :
sample2(int b);
friend void max(sample s1, sample2 s2)
};
Sample2:: sample(int b)
{
y=b;
}
void max(sample s1, sample2 s2)
{
if(s2.x>s2.y) cout<<"Data member in Object of class sample1 is larger"<<endl;
else
cout<<"Data member in Object of class sample2 is larger "<<endl;
}
void main()
{
clrscr();
sample1 obj(3);
sample2 obj(5);
max(obj1, obj2);
}
getch();
return 0;
}
I hope this information is helpful to you .