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:


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;

class B

    int getB;

               friend void gretest(A a1,B b1)

             void get_B()
             cout<<"enter the value of B"<<endl;

void gretest(A a1, B b1)

cout<<"the gretest number is"<<a1.getA;

cout<<"the gretest number is"<<b1.getB;

void main()

A a;
B b;

gretest(a b);



enter the number 12
enter the number 23

the gretest number is