Hi, I accidently came accross the friend function when I was initilizing a variable ... does anyone know what it does and how to use it?
Hi, I accidently came accross the friend function when I was initilizing a variable ... does anyone know what it does and how to use it?
If you want to give ( possibly unrelated ) classes or functions acces to protected members of a class you use the keyword friend.
Commonly used for stream inserters/extractors.
e.g
KurtCode:class foo{ public: foo():v(0) {} friend ostream & operator << ( ostream & str, foo & inst ); protected: int v; }; // without beeing friend to foo the stream inserter would not be allowed to access inst.v inline ostream & operator << ( ostream & str, foo & inst ) { return str << inst.v; }
Generally used in classes to give functions or other classes access to the private data members