FRIEND FUNCTION:
Access
to the private and protected members of a class by non-member
function is not allowed in normal. But it is possible to grant this
access to non-member function.
A
function which is declared as friend to a class have access to all
its members i.e. private and protected as well as public.
To
declare a function as friend, following syntax is used:
class
class_name
{ data
members and functions;
public:
friend
ret_type function_name(arg_list);
member
functions and variables;
};
Sample
Program:
#include<iostream>
using
namespace std;
class
sum
{
int
a, b;
public:
friend
int sumfrd(sum); // friend function
sum();
//constructor
}
sum::sum()
{
cout<<"Enter
a:";
cin>>a;
cout<<"Enter
b:";
cin>>b;
}
int
sumfrd(sum x)
{
return x.a+x.b;}
int
main()
{ sum
s;
cout<<"Sum
is: "<<sumfrd(s);
}
NOTE:
friend is a keyword in C++
The
circumstances in which friend functions are valuable:
-
Friend functions make creation of some types of I/O functions easier.
-
It is useful when we need to relate two classes in some sort.
-
It is useful in overloading certain types of operators.
No comments:
Post a Comment