Friend Function using C++
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.
#include
using namespace std;
class test
{
private:
int a;
int b;
public:
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;
p.setvalue();
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.
Project Files
/
Loading...
| .. | ||
| This directory is empty. | ||