C++ Friend Function

Advertisements

C++ Friend Function

Private members are accessed only within the class they are declared. Friend function is used to access the private and protected members of different classes. It works as bridge between classes.

  • Friend function must be declared with friend keyword.
  • Friend function must be declare in all the classes from which we need to access private or protected members.
  • Friend function will be defined outside the class without specifying the class name.
  • Friend function will be invoked like normal function, without any object.

Example of friend function


	#include<iostream.h>

	class RectangleTwo;

	class RectangleOne
	{
		int L,B;


		public:

		RectangleOne(int l,int b)
		{
		L = l;
		B = b;
		}

		friend void Sum(RectangleOne, RectangleTwo);
	};


	class RectangleTwo
	{
		int L,B;


		public:

		RectangleTwo(int l,int b)
		{
		L = l;
		B = b;
		}

		friend void Sum(RectangleOne, RectangleTwo);
	};



	void Sum(RectangleOne R1,RectangleTwo R2)
	{
		cout<<"\n\t\tLength\tBreadth";
		cout<<"\n Rectangle 1  :   "<<R1.L<<"\t  "<<R1.B;
		cout<<"\n Rectangle 2  :   "<<R2.L<<"\t  "<<R2.B;
		cout<<"\n -------------------------------";
		cout<<"\n\tSum   :   "<<R1.L+R2.L<<"\t  "<<R1.B+R2.B;
		cout<<"\n -------------------------------";
	}


	void main()
	{

		RectangleOne Rec1(5,3);
		RectangleTwo Rec2(2,6);

		Sum(Rec1,Rec2);

	}


	Output :

				 Length   Breadth
	  Rectangle 1 :      5          3
	  Rectangle 2 :      2          6
	  -------------------------------------------
		      Sum :      7          9
	  -------------------------------------------

				

In the above example, we have created two classes RectangleOne and RectangleTwo with a common friend function Sum().

Sum() method is receiving two objects, one of RectangleOne class and second of RectangleTwo class. This method is displaying the values of private data members of both the classes and also calculating the sum of both the rectangle classes.

Advertisement