Friend function in C++
-A friend function of a class is defined outside the class scope but it has the right to access all private and protected members of the class.
How make friend function ?
using 'friend' keyword we make friend function
program:
#include < iostream>
using namespace std;
class r4r {
int width;
public:
friend void display( Box box );
void set( double wid );
};
// Member function definition
void r4r::set(int wid) {
width = wid;
}
// Note: display() is not a member function of any class.
void display(r4r obj) {
cout << "Data is: " << obj.width << endl;
}
int main() {
r4r obj;
box.set(10);
// Use friend function to print the data
display(obj);
return 0;
}
Data is: 10