Friend Function in C++

In a C++ programming language private member of the class can accessed by member function.

Any non-member function can’t access private data member of the class.

But if we want to access the private data in non member function it is still possible by using the “friend function”.

A friend function can access private data of the class.

This can be done by declaring a non member function as a friend of the class whose private data is to accessed .

We can declare a non member function to friend function by using  “friend”   keyword.                                           

The function can be declared as friend function of one or more class.                                                                         

Properties of friend function

For the friend function there is no scope restriction means it can be called directly without using object.

friend function can’t access the public/private member directly.

It use object and dot operator to access the public/private member variable of the class.

Friendship is not shared for ex: if class X is declared friend of class Y, this dose not mean that Y has privileges to access private member of class X.


Description : In the above program,  show() is a non member function( it defined outside of class and called from main() function ) which is declared as a friend function of class “A”. 

Que: Write a C program  to exchange the values between two class by using friend function.


Categories C++