C++Tutorials

Friend Class and friend function in c++

As we know that a class cannot access the private members of other classes. Similarly, a class that doesn’t inherit another class cannot access its protected members.

What is Friend Class ?

A friend class is a class that can access the private and protected members of a class in which it is declared as friend. This is needed when we want to allow a particular class to access the private and protected members of a class.

Function Class Example

In this example we have two classes XYZ and ABC. The XYZ class has two private data members ch and num, this class declares ABC as friend class. This means that ABC can access the private members of XYZ, the same has been demonstrated in the example where the function disp() of ABC class accesses the private members num and ch. In this example we are passing object as an argument to the function.

#include <iostream>
using namespace std;
class XYZ {
private:
   char ch='A';
   int num = 11;
public:
   /* This statement would make class ABC
    * a friend class of XYZ, this means that
    * ABC can access the private and protected
    * members of XYZ class. 
    */
   friend class ABC;
};
class ABC {
public:
   void disp(XYZ obj){
      cout<<obj.ch<<endl;
      cout<<obj.num<<endl;
   }
};
int main() {
   ABC obj;
   XYZ obj2;
   obj.disp(obj2);
   return 0;
}

Output:

A
11

What is Friend Function ?

Similar to friend class, this function can access the private and protected members of another class. A global function can also be declared as friend as shown in the example below:

Friend Function Example

#include <iostream>
using namespace std;
class XYZ {
private:
   int num=100;
   char ch='Z';
public:
   friend void disp(XYZ obj);
};
//Global Function
void disp(XYZ obj){
   cout<<obj.num<<endl; 
   cout<<obj.ch<<endl;
}
int main() {
   XYZ obj;
   disp(obj);
   return 0;
}

Output:

100
Z

Advantage of friend function

  1. A friend function is used to access the non-public members of a class.
  2. It allows to generate more efficient code.
  3. It provides additional functionality which is not normally used by the class.
  4. It allows to share private class information by a non member function.
  5. It is used when two or more classes may contain members that are interrelated relative to others parts of the program.

Disadvantage of friend function

  1. A derived class does not inherit the friend function.
  2. Friend functions can not have a storage class specifier i.e they can not be declared as static or extern.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button