Home » Learn C++ » Friend Function

Friend Function

Friend Function:
A friend function can access all members of a class in which it is declared. It can also access private and protected members of all other classes even though it is not a member function of those classes. It is a non-member function. It is normally used when a function has to access private data of other classes.
A friend function is defined in a class. It is defined by using the keyword friend before the name of the function in the function decelerator. It can he defined anywhere in the class.
When a friend function is defined outside the class, it is defined without the scope resolution parameters (::).

Program:

# include
class y;
class z;
class x
private:
int m;
public:
x ( )
{m = 100;}
friend int abc (x, y, z) ;
};
class y
{
private:
int n;
public:
y ( )
{n = 10;}
friend int abc (x, y, z);
class z
{
private:
int 1;
public:
z ( )
{l = 20;)
friend int abc(x, y, z);
main ( )
x a;
y b;
z c;
cout << “sum of three numbers =” << abc (a, b, c);
}
int abc(x s1, y s2, z, s3)
{
return (sl.m + s2.n + s3.l);
}

 

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.