Friend Function
Friend Function
SYNTAX:
friend datatype functionname();
CODE:
#include<iostream>
using namespace std;
class base
{
int val1,val2;
public:
void getdata()
{
cout<<"W.A.P. to find Average value of two numbers using Friend function.\n\n\n";
cout<<"Enter value 1: ";
cin>>val1;
cout<<"Enter value 2: ";
cin>>val2;
}
friend float avg (base obj); // friend function
};
float avg(base obj)
{
return float(obj.val1 + obj.val2)/2;
}
int main()
{
base obj;
obj.getdata();
cout<<"Average value is: "<<avg(obj);
}
OUTPUT:
- Friend function is defined with keyword "friend"
 - It is declare inside of the class like other functions
 - It is global function
 - Function can access only public data of the class
 
SYNTAX:
friend datatype functionname();
CODE:
#include<iostream>
using namespace std;
class base
{
int val1,val2;
public:
void getdata()
{
cout<<"W.A.P. to find Average value of two numbers using Friend function.\n\n\n";
cout<<"Enter value 1: ";
cin>>val1;
cout<<"Enter value 2: ";
cin>>val2;
}
friend float avg (base obj); // friend function
};
float avg(base obj)
{
return float(obj.val1 + obj.val2)/2;
}
int main()
{
base obj;
obj.getdata();
cout<<"Average value is: "<<avg(obj);
}
OUTPUT:

0 Comments