Basically Friend functions can be introduced in C++ for handling some specific tasks which is related to class objects.
In C++, we know that private members cannot be accessed from the outside class.
That is a non-member function cannot have an access to the private data of a class.
However there could be a situation where we would like two classes to share a particular function.
For example consider a case where two classes, manager and scientist have been defined.
We would like to use a function income_ tax () to operate on the objects of both these classes.
In such situation, C++ allows the common function to be made friendly with both the classes. Such a function needs not be member of any these classes.
To make outside function friendly to a class, we have to simply declare this function as a friend of a class as shown below:
Class ABC
{
……
…..
Public:
……..
……..
Friend void xyz (void); //declaration
};
This function declaration should be preceded by the keyword friend.
The function is defined elsewhere in the program like a normal c++ function.
The function definition does not use either the keyword friend or the scope operator::
The functions that are declared with the keyword friend are known as friend function.
A function can be declared as a friend in any number of classes.
A friend functions, although not a member function has full access rights to the private members of the class.
In C++, we know that private members cannot be accessed from the outside class.
That is a non-member function cannot have an access to the private data of a class.
However there could be a situation where we would like two classes to share a particular function.
For example consider a case where two classes, manager and scientist have been defined.
We would like to use a function income_ tax () to operate on the objects of both these classes.
In such situation, C++ allows the common function to be made friendly with both the classes. Such a function needs not be member of any these classes.
To make outside function friendly to a class, we have to simply declare this function as a friend of a class as shown below:
Class ABC
{
……
…..
Public:
……..
……..
Friend void xyz (void); //declaration
};
This function declaration should be preceded by the keyword friend.
The function is defined elsewhere in the program like a normal c++ function.
The function definition does not use either the keyword friend or the scope operator::
The functions that are declared with the keyword friend are known as friend function.
A function can be declared as a friend in any number of classes.
A friend functions, although not a member function has full access rights to the private members of the class.