Coders Packet

Friend Function using C++

By Pratyasha Sahu

This code helps to understand the concept of friend function using C++. In this program the friend function is used to find the mean value of a sample.

Friend function helps in accessing both the private and protected data of a class, by declaring it as a friend.

The function declaration should be preceded by the keyword friend. A function can be declared as a friend in any number of classes. A friend function, although not a member function, has full access rights to the private members of the class.

using namespace std;
class test 
    int a;
    int b;
    void setvalue(){a=90;b=60;}
    friend float mean(test t);
float mean(test t) { return float(t.a+t.b)/2.0;}
int main()
    test p;
    cout<<"Mean valu="<<mean(p)<<endl;
return 0;

A friend function can be accessed even if it is defined outside class scope. Here it is used inside the class test and then returned outside the class' scope.

Download Complete Code


No comments yet