Friend Function in C++

In this tutorial, we will learn about friend function in C++ and what is the use of it.
let us see with some example program.

What is a friend function?

  • A friend function is a non-member function of class which can access the private members/data of class.
  • It is declared using the keyword friend in all classes from which we need to access the private data members.
  • It is defined outside of all class, without using friend keyword and scope resolution operator
  • Friend function will be called without using any object.

Class Member Function friends

Here are examples of a class member functions declared friends:

class DayOfYear
friend Date :: Date(const class DayOfYear&);
friend Date :: operator DayOfYear();
// ...

The friend declaration uses the class keyword to make a forward reference to the Date class, which has not been defined yet. This technique works because the DayOfYear class needs no details of the implementation of the Date class.

To Declare specific member functions as friends, the definition of the class with the member functions must be in scope. In this case, this means the Date class must be defined before the DayOfYear class .

Non-member Function friends

A class can specify that a non-member function in the program  is a friend to the class , as in this example:

class Time
// ...
freind void display(const Date&, const Time&);
// --non member function
void display(const Date& dt, const Time& tm)
 // has access to the private members
 // of date and time objects

Program designs often use functions that are members of neither class to bridge objects of the classes to perform some action that involves both classes’ data members. Sometimes those functions are members functions of a third class and other times those functions are non-members functions. Overload operator functions are frequently non-member functions that are declared as friends of the classes upon which the overload operators work.

Program to implement friend function in C++

using namespace std;
class A
private : int a,b;
public :void getData()
 cout<<"\n Enter any integers :";
friend  void display(A);
void display(A a1)
cout<<"\n a: "<<a1.a<<"\n b : "<<a1.b;
int main()
A a;

Output from Program:

Enter any integers: 4  5
 a: 4
 b: 5

Also, read:

Leave a Reply

Your email address will not be published. Required fields are marked *