What is a friend function?
- A friend function is a function that is specified outside a class but has the ability to access the class members’ protected and private data.
- A friend can be a member’s function, function template, or function, or a class or class template, in which case the entire class and all of its members are friends
Special features of friend functions:
- A friend function does not fall within the scope of the class for which it was declared as a friend. Hence, functionality is not limited to one class.
- The friend function can be a member of another class or a function that is outside the scope of the class.
- A friend function can be declared in the private or public part of a class without changing its meaning.
- Friend functions are not called using objects of the class because they are not within the class’s scope.
- Without the help of any object, the friend function can be invoked like a normal member function.
- Friend functions can use objects of the class as arguments
Declaration of a friend function in C++
class class_name
{
friend data_type function_name(arguments/s); //syntax of friend function.
};