Friend function: – The concept of encapsulation and data hiding detect that non-member function should not be allowed to access an object private and protected members the policy is, if we are not a member, we cannot gate it. Sometimes, this feature leads to considerable inconvenience in programming. Imaging that the user wants a function to operate own object of two different classes. As such time, it is recurred to allow function outside a class to access and manipulate the private member of the class. In C++, this is achieved by using the concept of friends.

Once of the convenient and a controversial feature of C++ is allowing to access even the private member of a class is called friend function. The friend function permits a function or all the function of another class to access a different class’s private member. The friend function operate with the keyword friend. This keyword is not used with function definition some important feature of friend function are-

  1. The scope of a friend function is not limited to the class in which it has been declare as a friend.
  2. Friend function cannot be called using the object of the class, it is not in the scope of the class. It can be invoked like a normal function without the use of any object.
  3. Unlike class member function, it cannot access the class member directly. However, it can use the object and the dot operator with each member name to access both private and public member function.

Friend class: – When specific member function of one class should be friend function of another class, it must be specified. Explicitly using scope resolution operator, friend function permit an exception to rules data encapsulation. The friend keyword allow a function or all of the function to another class to manipulate the private member of the original class and this type of manipulation of multiple classes are called friend class.

Advertisements