Friend function in C++

Throughout this blog, we will be learning about the friend function in the C++ language. An object-oriented programming language prohibits access to private members from outside the class. The friend function plays a major role in this situation.

What is the friend function?

A function that accesses private members of a class but is not itself a member of the class is called the 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.
// sum of two numbers using the friend function  
  
#include<iostream.h>  
#include<conio.h>  
  
class B; //declre class b  
  
class A  
{  
    private:  
        int a;   // private data  
    public:  
        void setData()   // member function  
        {  
            cout<<"Enter 1st number: ";  
            cin>>a;  
        }  
        friend void sum(A ob1,B ob2); //declare friend function  
};  
class B  
{  
    private:  
        int b; //private data  
    public:  
        void setData()       // member function  
        {  
            cout<<"Enter 2nd number: ";  
            cin>>b;  
        }  
        friend void sum(A ob1,B ob2);  // declare friend function  
};  
void sum(A ob1,B ob2)  
{  
    int s=ob1.a+ob2.b; //accessing private data  
    cout<<"sum: "<<s<<endl;  
}  
  
void main()  
{  
    clrscr();  
    A obj1;  
    B obj2;  
    obj1.setData();  
    obj2.setData();  
    sum(obj1,obj2); //invoking the friend function  
    getch();  
} 

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

Leave a Reply

Your email address will not be published.