#include<iostream.h>
class Sample
{
int a;
int b;
public:
void setvalue()
{
a=25;
b=40;
}
friend int avg(Sample s);
};
int avg(Sample s)
{
return(s.a+s.b)/2;
}
Void main()
{
Sample x;
x.setvalue();
cout<<avg(x);
}
************************************
Friend function
With the use of a friend function we can access the private data of a class.
class Abc
{
….
….
public:
….
friend void xyz();/declaration
};
Characteristics of friend function
>It is not in the scope of the class to which it has been declared
>Since it is not in the scope of the class,it cannot be called using the object of that class
>It can be invoked like a normal function without the help of any object
>But we cannot access the member names directly & has to use an object name & dot operator
(e.g. A.x)
>Usually it has the objects as arguments