Friend Functions With Example Syntax And Program

Explain Friend Functions with Example Syntax and Program


Friend Functions :- 


1.     Friend functions are Not member functions of any class, but they can access the private, protected and public members of the class.
2.     They are declared using “ friend “ keyword.
3.     They Don’t belong to any specific Class.
4.     They can be invoked as ordinary functions, with out using any object.
5.     They can be defined outside the Class, here also they are defined like ordinary functions and Not like member functions.
1.    The access specifiers does not effect the visibility of Friend Functions.
2.    Usually a friend function receives the object as arguments.
9.    Syntax :-
friend   return-type  function-name ( input-arguments ) ;
10. member function of one class can be defined as friend function of another class.In such case they are
 defined using scope resolution operator as shown below.
class X
{    ………
    int fun1();    //member fun of X
};
class Y
{   ………..
   …………
   friend int X: :fun1();
};

Example:
#include<iostream.h>
#include<conio.h>
class sample
{     int a,b;
      public:
              void get()
              { cin>>a>>b;  }
             void show()
            {  cout<<a<<b;  }
          friend void swap(sample s);
};
void swap( sample  s1)
{  int temp=s1.a;
        s1.a =s1.b;
        s1.b = temp;
   cout<<”a=”<<s1.a<<”b=”<<s1.b;
}
void main()
{   clrscr();
    sample s2;
   s2.get();
   cout<<” before swapping:”<<endl;
    s2.show();
    cout<<”After swapping:”
    swap(s2);            //function call swap(s2) passes the object s2 by value to the friend function.
   getch();
}

Note: Actual swapping can be done by reference or address, we can make friend void swap( sample  &); or swap( sample *);

Labels: