FRIEND FUNCTION
We know that private member cannot be access from out side the class.That is
a non member function cannot have an access to the private data of a class,but
there may be some situation where we would like two classes to share a
particular function.In such situation c++ allows the common function to be made
friendly with both the classes,that allows to have access to the private data
of these classes.Such a function need not be a function of any of these
classes.
To declear a friend function the function decided by the keyword friend.the definition does not
used the keyword friend or the scope resulation operator(::) .A function can be
decleare as a friend in any number of classes.All the a friend function of
class is a but it has full access to the private members of class.
Charaterstatices
of friends function :-
· A friend function
is not the scope of class to his it has been decleare as friend.
·
Since it is not
in the scope of the class, it cannot be called using the object of class it can
be called like a normal function without the help of any function
·
It cannot access
data members directly and has to used an object and dot membership operator
with each member name.
·
Friend function
either in the public or private part of th class without effecting its meaning.
·
Usually it has
the object as arguments.
Friend function
with single class
#include<iostream.h>
#include<conio.h>
Class test
{
Int a,b;
Public:
Void getdata()
{
Cout<<”enter
two values”;
Cin>>a>>b;
}
Friend float
mean(test t);
};
Float mean(test
t)
{
Float x;
X=(t.a+t.b)/2;
Return x;
}
Void main()
{
Test t;
t.getdata();
cout<<”\n
mean value=”<<mean(t);
getch();
}
Friend function
double class :-
#include<iostream.h>
#include<conio.h>
Class test2 ;
Class test1
{
Int x;
Public:
Void getdata()
{
Cout<<”enter
any value”;
Cin>>x;
}
Friend void sum(
test1, test2);
};
Class test2
{
Int y;
Public:
Void getdata()
{
Cout<<”\n
enter any value”;
Cin>>y;
}
Friend void sum(
test1, test2);
};
Void sum(test1
t1, test2 t2)
{
Int total;
total=t1.x +
t2.y;
cout<<”\n
sum=”<,total;
}
Void main()
{
Test t1;
Test2 t2;
T1.getdata();
T2.getdata();
Sum(t1,t2);
Getch();
}
Comments
Post a Comment