Close
Close

Friend Class and Function in C++


If a function is defined as a friend function of a class, then that function can access all the private and protected data.

To make a function as a friend of a class, it is declared inside the class either in private or in public section with keyword friend before its declaration as follows.

class Temperature
{
    int celsius;
    public:
        Temperature()
        {
            celsius = 0;
        }
        friend int temp( Temperature )     //declaring friend function
};

Here temp is a friend function of the class Temperature. So, it can access all the private and protected members of the class.

Let's see an example.

#include <iostream>

using namespace std;

class Temperature
{
	int celsius;
	public:
		Temperature()
		{
			celsius = 0;
		}
		friend int temp( Temperature );   // declaring friend function
};

int temp( Temperature t )     // friend function definition
{
	t.celsius = 40;
	return t.celsius;
}

int main()
{
	Temperature tm;
	cout << "Temperature in celsius : " << temp( tm ) << endl;
	return 0;
}
Output
Temperature in celsius : 40

Here we declared a function 'temp' as the friend function of the class 'Temperature'. In the friend function, we directly accessed the private member celsius of the class 'Temperature'.
When the first statement of the main function created an object 'tm' of the class 'Temperature' thus calling its constructor and assigning a value 0 to its data member celsius.
The second statement of the main function called the function 'temp' which assigned a value 40 to celsius.

We can also have the same friend function of two classes as shown in the next example.

#include <iostream>

using namespace std;

class B;       //declaration of class B

class A
{
	int value;
	public:
		A()
		{
			value = 5;
		}
		friend int sum(A, B);     // declaring friend function
};

class B
{
	int value;
	public:
		B()
		{
			value = 3;
		}
		friend int sum(A, B);     // declaring friend function
};

int sum( A v1, B v2 )             // friend function definition
{
	return (v1.value + v2.value);
}

int main()
{
	A a;
	B b;
	cout << "Sum : " << sum( a, b ) << endl;
	return 0;
}
Output
Sum : 8

In this example, we declared sum() as a friend function of the classes A and B. So, this function can now access the private and protected members of both these classes. The objects of both the classes are passed into as an argument to the function.
First, we created an object for both the classes, thus calling their respective constructors and initializing the values of their respective data member value to 5 and 3. The function 'sum' then returned the sum of the data members of the two classes by calling the data members of the two classes by their respective objects.

Note that we declared class B before defining class A because in the body of class A, the friend function takes the parameters 'A' and 'B'.

Friend Class


We can also make a class a friend of another class. In that case, all the member function of the class declared as friend become the friend functions of the other class.

Let's see how to make a class a friend of another.

class A
{
    friend class B;

};

class B
{

};

Class B is declared as a friend of class A in the above code. So, now all the member functions of class B became friend functions of class A.

Let's see an example of a class friend.

#include <iostream>

using namespace std;

class Square
{
	friend class Rectangle;      // declaring Rectangle as friend class
	int side;
	public:
		Square ( int s )
		{
			side = s;
		}
};

class Rectangle
{
	int length;
	int breadth;
	public:
	int getArea()
	{
		return length * breadth;
	}
	void shape( Square a )
	{
		length = a.side;
		breadth = a.side;
	}
};

int main()
{
	Square square(5);
	Rectangle rectangle;
	rectangle.shape(square);
	cout << rectangle.getArea() << endl;
	return 0;
}
Output
25

We declared Rectangle as a friend class of Square. Thus now, all the functions of Rectangle can directly access any private member of Square.
In the main function, the first statement created an object 'square' of the class Square, thus calling its constructor and assigning 5 to its data member side.
The second statement in the main function created an object 'rectangle' of the class Rectangle.
In the third statement, 'rectangle' called the function shape() with the object of the class Square passed as its argument. In the 'shape()' function, the value of 'side' (private data member of Square) was assigned to length and breadth. The fourth statement called the function 'getArea' of the class Rectangle.

Class Members as Friend


We can also make a function of one class as a friend of another class. We do this in the same way as we make a function as a friend of a class. The only difference is that we need to write class_name :: in the declaration before the name of that function in the class whose friend it is being declared. The friend function is only specified in the class and its entire body is declared outside the class. It will be clear from the example given below.

class A; // forward declaration of A needed by B

class B
{
    display( A a ); //only specified. Body is not declared
};

class A
{
    friend void B::display( A );
};

void B::display(A a) //declaration here
{
}

Let's see its example.

#include <iostream>

using namespace std;

class A; // forward declaration of A needed by B

class B
{
    public:
        void display(A obj); //no body declared
};

class A
{
    int x;
    public:
        A()
        {
            x = 4;
        }
        friend void B::display(A);
};

void B::display(A obj)
{
    cout << obj.x << endl;
}

int main()
{
    A a;
    B b;
    b.display(a);
    return 0;
}
Output
4
You need to run this code using gcc filename.cpp -lstdc++ -o filename
To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.

Ask Yours
Post Yours
Doubt? Ask question