C++

The C++ Friend Class And Friend Functions – Q&A

A class cannot access the secret members of another class, as is well known. A class that does not inherit from another class also cannot access that class’s protected members.

Friend Class:

A class that has been designated as a friend can access the protected and private members of the class in which it is present. This is required when we wish to grant a certain class access to a class’s private and protected members.

Function Class Illustration

We have two classes in this example: XYZ and ABC. The XYZ class designates ABC as a buddy class and has two private data members named ch and num. In the example where the function disp() of the ABC class accesses the private members num and ch, it can be seen that ABC can access the private members of XYZ. In this illustration, we are passing object to the function as an argument.

#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

Friend Function:

Like the friend class, this function has access to a class’s protected and private members. Additionally, a global function may be designated as a buddy, as in the example below:

Friend Function Illustration

#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

Related Articles

Leave a Reply

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

Back to top button