Friend function in C++ with easy example! explained.

Friend function in c++.

Friend function in the class are the function which are defined outside the class even though it has all the rights to access the private or protected function in side the class.
The friend function call is takes place inside the class itself, after at the time of compiling the our programm the compiler goes to function call which invokes the friend function after that the function definition is compiled inside the compiler.

Friend function does not belong to any class,but it can accessed and declared anywhere.

A simple example:

Write a programm to find out greatest of two number using the friend function:

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

class B;       // I declared because at the of demand of B in class there is no further declaration
class A          //Here I am declaring the first class
{
        int getA;
        public:        // it must be public for accessible
       
            friend void gretest (A a1, B b1)

           void get_A();
             {
              cout<<"enter the value of A"<<endl;
              cin>>getA;
             }
};

class B
{

    int getB;

               public:
               friend void gretest(A a1,B b1)

             void get_B()
            {
             cout<<"enter the value of B"<<endl;
             cin>>getB;
             }
}


void gretest(A a1, B b1)
{

 if(a1.getA>b1.getB)
{
cout<<"the gretest number is"<<a1.getA;
}

else
{
cout<<"the gretest number is"<<b1.getB;
}

void main()
{

A a;
B b;
clrscr();

a.getA();
b.getB();
gretest(a b);

getch();

}


op:
enter the number 12
enter the number 23

the gretest number is
23