Syntax error Difference Between Friend Function and Friend Class

Difference Between Friend Function and Friend Class



In this post, we will understand the difference between Friend function and Friend class.

Friend Function

  • It is usually used with operator overloading operation.

  • It is used with the ‘friend’ keyword.

  • It helps give a non-member function the access to the private members of the class.

  • It has to be declared before it is used.

  • It is used to access private and protected members of the class.

  • It can be a global function or a function in another class.

Example

class Node
{
   private:
   int val;
   Node* next;

   // Other members of Node Class //
   friend int LinkedList::search();
   // Only search method of linkedList
   // can be used to access the internal members
};

Friend Class

  • It is a class that is used with ‘friend’ keyword.

  • It is not necessary to declare it before using it.

  • A friend class is used when a class is created as an inherited class from another base class.

  • It is used to access private and protected members of the class.

Example

class Node
{
   private:
   int val;
   Node* next;
   /* Other members of Class */

   // The class can access private members of
   //Node friend class LinkedList;
};
Updated on: 2021-03-23T08:01:22+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements