Thursday, 29 May 2014

Friend function

                Friend function is used to access private data members of the class. Friend is not a member function but it is declared in the class and defined outside the class. For friend class click on the link.


#include<conio.h>
#include<iostream>
using namespace std;
class avg
{
                private:
                        float a,b;
                public:
                                avg(){a=0.0,b=0.0;}
                                void get()
                                {
                                                cout<<"\n enter the value of a and b: ";
                                                cin>>a>>b;
                                }
                                friend float avrg(avg x); //friend function declaration.
};

float avrg(avg x) // friend definition.
{
                return (x.a+x.b)/2;
}


int main()
{
                avg A;
                A.get();
                cout<<"\n the average value of these two numbers is :"<<avrg(A);
                getch();
                return 0;

}

No comments:

Post a Comment