Thursday, 29 March 2018

Friend function in c++



FRIEND FUNCTION:

Access to the private and protected members of a class by non-member function is not allowed in normal. But it is possible to grant this access to non-member function.
A function which is declared as friend to a class have access to all its members i.e. private and protected as well as public.
To declare a function as friend, following syntax is used:
class class_name
             {      data members and functions;
               public:
                    friend ret_type function_name(arg_list);
                    member functions and variables;
              };
Sample Program:
#include<iostream>
using namespace std;
class sum
{
int a, b;
public:
friend int sumfrd(sum);                          // friend function
sum();                                                     //constructor
}
sum::sum()
{
cout<<"Enter a:";
cin>>a;
cout<<"Enter b:";
cin>>b;
}
int sumfrd(sum x)
{ return x.a+x.b;}

int main()
{   sum s;
     cout<<"Sum is: "<<sumfrd(s);
}


NOTE: friend is a keyword in C++

The circumstances in which friend functions are valuable:
  1. Friend functions make creation of some types of I/O functions easier.
  2. It is useful when we need to relate two classes in some sort.
  3. It is useful in overloading certain types of operators.

No comments:

Post a Comment

POLYMORPHISM IN C++

POLYMORPHISM IN C++ C++ achieves polymorphism through: i) Function overloading ii)Operator overloading By the...