Friend function
- Friend function declaration can appear anywhere in the class.
- But a good practice would be where the class ends.
- An ordinary function that is not the member function of a class has no privilege to access the private data members, but the friend function does have the capability to access any private data members.
- The declaration of the friend function is very simple.
- The keyword friend in the class prototype inside the class definition precedes it.
- Example to Demonstrate working of friend Function
/* C++ program to demonstrate the working of friend function.*/#include <iostream>
using namespace std;
class Distance {
private:
int meter;
public:
Distance(): meter(0){ }
friend int func(Distance); //friend function
};
int func(Distance d){
//function definition
d.meter=10; //accessing private data from non-member function
return d.meter;
}
int main(){ Distance D;
cout<<"Distace: "<<func(D);
system("pause");
return 0;
}