Friend Function In C++

This blog demonstrates friend function in C++. Private members of a class cannot access outside the class but using the friend function it is possible.

Introduction

In this blog, we will learn about friend function in the C++ language. In object oriented programming language private members cannot access from outside the class. In this situation friend function plays a major role.

What is friend function?

A function that accesses private members of a class but is not itself a member of class is called friend function.

Characteristics of a friend function

  • It is not declared as a member of any class.
  • It is invoked like a normal function using the friend keyword.
  • It can access the private members of a class using the object name.
  • It has the objects as arguments.

Example

This example shows how to access private members of a class using the friend function.

  1. // sum of two numbers using the friend function  
  2.   
  3. #include<iostream.h>  
  4. #include<conio.h>  
  5.   
  6. class B; //declre class b  
  7.   
  8. class A  
  9. {  
  10.     private:  
  11.         int a;   // private data  
  12.     public:  
  13.         void setData()   // member function  
  14.         {  
  15.             cout<<"Enter 1st number: ";  
  16.             cin>>a;  
  17.         }  
  18.         friend void sum(A ob1,B ob2); //declare friend function  
  19. };  
  20. class B  
  21. {  
  22.     private:  
  23.         int b; //private data  
  24.     public:  
  25.         void setData()       // member function  
  26.         {  
  27.             cout<<"Enter 2nd number: ";  
  28.             cin>>b;  
  29.         }  
  30.         friend void sum(A ob1,B ob2);  // declare friend function  
  31. };  
  32. void sum(A ob1,B ob2)  
  33. {  
  34.     int s=ob1.a+ob2.b; //accessing private data  
  35.     cout<<"sum: "<<s<<endl;  
  36. }  
  37.   
  38. void main()  
  39. {  
  40.     clrscr();  
  41.     A obj1;  
  42.     B obj2;  
  43.     obj1.setData();  
  44.     obj2.setData();  
  45.     sum(obj1,obj2); //invoking the friend function  
  46.     getch();  
  47. }  

Friend Function In C++

In this blog, I will try to explain how to access private data of a class using the friend function in C++ language. Thanks for reading.