Friend Functions
Friend Function A function is said to be a friend function of a class if it can access the members (including private members) of the class even if it is not the member function of this class. In other words, a friend function is a non-member function that has access to the private members of the class.
Characteristics of a friend function:
- A friend function can be either global or a member of some other class.
- Since friend function is not a part of the class, it can be declared anywhere in the public, private and protected section of the class.
- It cannot be called by using the object of the class since it is not in the scope of the class.
- It is called a normal function without the help of any object.
- Unlike member functions, it cannot access member names directly. So, it has to use an object name and dot operator with each member name (like A.x)
- It, generally, takes objects as arguments.
Sample Code
class sample
{
int a;
int b;
public:
void setvalue()
{
a = 25;
b = 40;
}
friend float mean(sample s);
};
};
float mean(sample s)
{
return float(s.a + s.b)/2;
}
void main()
{
sample x;
x.setvalue();
cout<<"Mean value = "<<mean(x);
return 0;
}
Output:
Mean value = 32.5
Furthermore, a fried function also acts as bridging between two classes. For example, if we want a function to take objects of two classes as arguments and operate on their private members, we can inherit the two classes from the same base class and put the function in the base class. But if the classes are unrelated, there is nothing like a friend function. For example,
Source Code
#include<iostream>
using namespace std;
class beta;
class alpha
{
int data;
public:
void setdata(int d)
{
data =d;
}
friend int sum(alpha,beta);
};
class beta
{
int data;
public:
void setdata(int d)
{
data=d;
}
friend int sum(alpha,beta);
};
int sum(alpha a,beta b)
{
return a.data+b.data;
}
int main()
{
alpha a;
a.setdata(5);
beta b;
b.setdata(10);
cout<<"Sum :"<<sum(a,b);
}
Output
Sum :15
Post A Comment:
0 comments so far,add yours