C++ Friend Class

Advertisements

C++ Friend Class

Like friend function, a class can also be a friend of another class. A friend class can access all the private and protected members of other class.

In order to access the private and protected members of a class into friend class we must pass on object of a class to the member functions of friend class.

Example of C++ friend class


	#include<iostream.h>

	class Rectangle
	{
		int L,B;

		public:
		Rectangle()
		{
			L=10;
			B=20;
		}

		friend class Square;        //Statement 1
	};

	class Square
	{
		int S;

		public:
		Square()
		{
			S=5;
		}

		void Display(Rectangle Rect)
		{
			cout<<"\n\n\tLength : "<<Rect.L;
			cout<<"\n\n\tBreadth : "<<Rect.B;
			cout<<"\n\n\tSide : "<<S;
		}
	};

	void main()
	{

		Rectangle R;
		Square S;

		S.Display(R);       //Statement 2

	}

	Output :

		  Length : 10
		  Breadth : 20
		  Side : 5

In the above example, we have created two classes Rectangle and Square. Using statement 1 we have made Square class, a friend class of Rectangle class. In order to access the private and protected members of Rectangle class into Square class we must explicitly pass an object of Rectangle class to the member functions of Square class as shown in statement 2.

This is similar to passing an object as function argument but the difference is, an object (R) we are passing as argument is of different class (Rectangle) and the calling object is of different class (Square).

Advertisement