Friend Function in C++ with Example


A friend function is a function that is not a member of a class but has access to the class's private and protected members. However, a situation can be created where two classes could share a common function. For instance, assume two classes called Engineer and Postmaster. Here we have to use the function called salary to operate on the objects of both these classes.

Friend functions are not considered class members and they are normal external functions that are given special access privileges. Friends are not in the class's scope. They are not called using member-selection operators (. and ->) unless they are members of another class.

A friend function is declared by the class that is granting access. They friend function declaration can be placed anywhere in the class declaration.

Some of the special characteristics of a friend function are

  • − A friend function is a function that has full access to the private members of a class but not itself a member of that class.
  • −A friend function can be defined anywhere in the C++ program and not necessarily immediately after the class definition.
  • − The friend function doesn't have this pointer.
  • − A function can be friend of more than one class
  • − The friend function accepts objects as arguments.

Simple Program for Friend Function Using C++ Programming

#include<iostream> using namespace std; class Friend_Function{ int a; public: Friend_Function(int x){ a = x; } void print(){ cout<<"The value of is :"<<a<<endl; } friend void msg(Friend_Function s1); }; void msg(Friend_Function s1){ s1.a = 44; // private data accessible in a friend function cout<<"The value of a is :"<<s1.a; // private data accessible in a friend function } int main(){ Friend_Function s1(10); s1.print(); msg(s1); return 0; }

Output:-

The value of is :10
The value of a is :44

Explanation of the program

The msg() function is a friend function to the class Friend_Function. It has been declared inside the Friend_Function class. It accepts arguments here only objects i.e. s1. It does access the private data member of sample class. Only a friend function can do so.