Friend Function in C++ AD
Friend Function in C++ AD
C++
Manoj Pawaiya
Lect.(IT)
IET davv, Indore
mob- 9926839606
Friend Functions
•A friend function is a function that is not a member
of a class but has access to the class's private and
protected members. Friend functions are not
considered class members; they are normal external
functions that are given special access privileges.
Friends are not in the class's scope, and they are not
called using the member-selection operators
(.and –>) unless they are members of another class.
The friend declaration can be placed anywhere in
the class declaration.
class Point
{
friend void ChangePrivate( Point p );
public:
Point( void ) : m_i(0) {}
void PrintPrivate( void )
{
cout << m_i << endl;
}
private:
int m_i;
};
void ChangePrivate ( Point i )
{ i.m_i++;
}
int main()
{ Output
Point sPoint; 0
sPoint.PrintPrivate(); 1
ChangePrivate(sPoint);
sPoint.PrintPrivate();
}
Characteristics of friend function
It is not in the scope of the class to which it has declared
as friend.
Since it is not in the scope of the class, it can not be
called using the object of that class.
It can be invoked like a normal function without the
help of any object.
Unlike member functions, it can not access the member
names directly and has to use an object name and dot
membership operator with each member name
( e.g. P.m_i).
It can be declare either in the public or the private part
of a class without affecting its meaning.
It has the objects as arguments.
A function friendly to two classes
Manoj Pawaiya
Lect.(IT),iet davv