WRITE A PROGRAM FOR FRIEND FUNCTION IN C++

 Que- what is friend function?

Ans-  A friend function is a special function in c++ which is not a member of class but allow us to access the private and protected members of a class . Friend Function Like friend class, a friend function can be given a special grant to access private and protected members. A friend function can be: 

a) A member of another class 

b) A global function 

Friend function is declared in any sections of a class like in private section, public section and protected section. Friend function is not mutual means if class first is friend of class second that doesn't mean class second is automatically friend of class first. Friend function don't work in Java .

Some advantages and disadvantage of using friend function in c++ are given below:-

Advantages:-

  1.  A friend function is able to access members without the need of inheriting the class.
  2. Friend function acts as a bridge between two classes by accessing their private data.
  3. It can be used to increase the versatility of overloaded operator.
  4. It can be declared either in the public or private or protected part of class.

Disadvantages:-

  1. Friend functions have access to private members of a class from outside the class which violates the law of the data hiding.
  2. Friend functions cannot do any run time polymorphism in its members. 

 Example of friend function is :-

#include<iostream>
using namespace std;

class krishna
{
  int num1, num2;
public:
void getdata ()
{
cout<<"enter a numbers:";
cin>>num1;
cout<<"enter a numbers:";
cin>>num2;
}
friend int fun (krishna ob);

};
int fun (krishna ob)
{
   return int (ob.num1+ob.num2) ;
}
int main()
{
    krishna on;
    on. getdata ();
    cout<<"sum is "<<fun(on);
    return 0;
}

Result:-



Post a Comment

Previous Post Next Post