15
Friend void xyz(void); //declaration
};
➢ The functions that are declared with the keyword friend are known as friend functions.
➢ A function can be declared as friend in any number of classes.
➢ A friend function, although not a member function, has full access rights to the private members
of the class.
A friend function possesses certain special characteristics:
1) It is not in the scope of the class to which it has been declared as friend.
2) Since it is not in
the scope of the class, it cannot be called using the object of that class.
3) It can be invoked like a normal function without the help of any object.
4) Usually, it has objects as arguments.
5) It cannot access the member names directly and has to use an object name and dot
membership operator with each member name (e.g A.x)
Example:
#include
using namespace std;
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.0);
}
int main ( )
{
sample x;
x . setvalue( );
cout<<"mean value="<return(0);
}
Member functions of one class can be friend function of another class. In such cases, they are defined
using the scope resolution operator.
16
E.g.
class X
{
………..
………..
int fun1( ); //member function of x
………..
};
class Y
{ …………..
……………
friend int x : : fun1( ); //fun1 ( ) of X is
friend of Y
};
Here, fun1( ) is a member of class X and friend of class Y
Dostları ilə paylaş: