In this topic we will Discuss Best concept and program of Friend Function and Friend Class in C++ with example.
Friend Function :-
- It is a non-member Function which allows to access private Data member outside of the class.
- Friend Function is invoked like a simple Function.
- Friend function is declared with ‘friend’ keyword inside a class in private or public section.
- Friend Function Requires an object as a function Argument.
Properties of Friend Function
There are following properties of friend function.
- Friend function is invoked without objects.
- Friend function can’t access members directly i.e it requires an object to access private or public members of the class.
- Friend function can be declared in private of public section.
- Friend function is rarely used because it violets the rule of Data hiding and Encapsulations.
Syntax:-
class class_name
{
friend return_type function_name(Arguments);
};
Example
class num
{
private:
int a,b,c;
friend void sum(num);
};
void sum(num obj)
{
Accessible private or public data
}