A friend function is a function that has access to the private members of a class but is not itself a member of that class.
Syntax:
friend returntype fun_name(args);
Characteristics:
o It is not in the scope of the class to which it has been declared as friend.
o Since it is not in the class, it need not be called by using object of class.
o It can be invoked like a normal function
o Usually friend functions has objects as arguments
o A function can be a friend of more than one class.
o Private data is accessed using the dot operator
/* friend function using single class*/
#include<conio.h>
class sample
{
int a,b;
friend void print(sample);
};
void print(sample s)
{
s.a=10;
s.b=20;
cout<<"a="<<s.a;
cout<<"b="<<s.b;
}
void main()
{
clrscr();
sample s;
print(s);
getch();
}
/* friend function using two class*/
#include<conio.h>
class second; //forward declaration
class first
{
int a;
public:
void geta()
{
cout<< "enter a value:";
cin>>a;
}
friend void big(first ,second); //comparing 2 objects of class types.
};
class second
{
int b;
public:
void getb()
{
cout<< "enter b value:";
cin>>b;
}
friend void big(first ,second); //comparing 2 objects of class types.
};
void big( first f,second s)
{
if(f.a>s.b)
cout<< "a is big";
else if(s.b>f.a)
cout<< "b is big";
else
cout<< "both are equal";
}
void main()
{
first f;
second s;
f.geta();
s.getb();
big(f,s);
getch();
}
FRIEND CLASSES:
If we make the entire class as a friend then automatically all the member functions of the class become friends.
Friendship is granted not taken i.e., for class B to be a friend of class A, class A must explicitly declare that class B is its friend.
/* friend classes */
No comments:
Post a Comment