I am confused on friend function and friend class in c++.
and in my coding experience, i never used friend. and even not found others's code contains friend.
i know the basic usage and idea of friend.
and typical demo is like:
#include <iostream>
using namespace std;
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
void Box::setWidth( double wid )
{
width = wid;
}
void printWidth( Box box )
{
cout << "Width of box : " << box.width <<endl;
}
int main( )
{
Box box;
box.setWidth(10.0);
printWidth( box );
return 0;
}
in this case, i dont know what's the meaning to use friend, i can define printWidth as:
void Box::printWidth() {
cout << "Width of box : " << width <<endl;
}
i think this will be better. and define it as friend wont make it more flexiable or universal.
So, can you provide a solid example to explain why i should use friend, or in what siutation, friend is a better or elegant solution?