What is a friend function?

Asked 07-Dec-2019
Viewed 595 times

1 Answer


0

Friend class and function in C++

However, A function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the function.

Using the keyword friend compiler shows that the given function is the friend function.
To access data in this way, a friend function must be declared inside the body of a class starting with the keyword friend.
Friend Class
Where a friend class can access private and protected members of other class in which it is declared as friend. This is sometimes useful to allow a particular class to access private members of other class. Like this, a LinkedList class may be allowed to access private members of Node.
Declaration of friend function in C++
class class_name    

{
    friend data_type function_name(argument/s); // syntax of friend function.
};    
Characteristics of a Friend function:
  • A function is not in the scope of the class to which it has been declared as a friend.
  • That can't be called using the object as it is not in the scope of that class.
  • That can be invoked like a normal function without using the object.
  • That cannot access the member names directly and has to use an object name and dot membership operator with the member name.
  • This can be declared either in the private or the public part.
Following are some important points about friend functions and classes:
  • The Friend function should be used only for limited purpose. The too much functions or external classes are declared as friends of a class with protected or private data, it lessens the value of encapsulation of separate classes in OOPs(object-oriented programming).  
  • The Friendship is not mutual. When class A is a friend of B, then B doesn’t become a friend of A automatically.  
  • The Friendship is not inherited (See this for more details)  
  • That is the concept of friends is not there in Java.