C++ | Friend Classes

Function Class Example:1
In this example, we have two classes “one” and “two”. The class “one” has two private data members a and b, this class declares “two” as friend class. This means that “two” can access the private members of “one”, the same has been demonstrated in the example where the function disp() of “two” class accesses the private members a and b. In this example, we are passing an object as an argument to the function.

#include<iostream>
#include<conio.h>
using namespace std;
class two;
class one
{
	private:
    	int a,b;
	public:
    	void set()
     	{
     		//a=10;
       		//b=20;
       		//input can be taken
       		cout<<"Enter value of a and b ";
       		cin>>a>>b;
     	}
     	/* 
		This statement would make class "two"
		a friend class of "one", this means that
		"two" can access the private and protected
		members of "one" class. 
		*/
       friend two;
};
class two
{
	public:
    	void disp(one e)
     	{
     		cout<<"Private data element of class one "<<e.a<<","<<e.b<<endl;
     	}
};
int main()
{
  	one o1;
  	two t1;
  	o1.set();
  	t1.disp(o1);
  	return(0);
}
/* Output */
Enter value of a and b 100
200
Private data element of class one 100,200

Function Class Example:2
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<<"To Access private data elements of class XYZ"<<endl;
			cout<<obj.ch<<endl;
      		cout<<obj.num<<endl;
   		}
};
int main() {
   ABC A1;
   XYZ X1;
   A1.disp(X1);
   return 0;
}
/* Output */
To Access private data elements of class XYZ
A
11