What is a friend function?
A friend is a function that is not a member of a class, but has access to the private members of the class.
· A friend function of a class can be a global function.
· Access specifier do not apply to the friends of a class.
· This friendship is unidirectional.
A friend function can access the private and protected data of a class. We declare a friend function using the friend keyword inside the body of the class.
Friend Function Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Declaration of a friend function in C++
class class_name
{
friend data_type function_name(arguments/s); //syntax of friend function.
};
Brief Syntax:-
• friend is a keyword to denote that this function is a friend function.
• dataType is the function’s data type.
• Function_Name is the name of the function being made a friend of the class.
• arg list is the arguments that are passed.
Example 1: Friend function declaration
Output:
Mean value: 40
Example 2: Friend function declaration
Output:
X=5
Y=2
Example 3: Friend function declaration
Output:
Sum: 25
Friend functions of another class by defining the function using the scope resolution operator as shown below:
class class_Name1
{
int function_Name();
};
Class class_Name2
{
Friend int class_Name1::function_Name();
};
Example:
Output:
The value of b is: 12
0 Comments
Thanks for Supporting me