FAQ 19.05 What is a friend function?

A friend function is a nonmember function that has been granted access to a class's non-public: members. This improves an interface without breaking encapsulation.

For example, the syntax most objects use for printing is cout << x, where x is the object being printed and cout is the output stream (ostream) on which the object is being printed. This printing service is provided by operator<<, which needs to be a friend function of the class of x rather than a member function of the class of x, because the ostream needs to be on the left side of the << operator and the object being printed on the right side. In general, binary operators can be member functions only if the member function is attached to the left hand argument of the operator.

 #include <iostream> #include <cstdlib> using namespace std; class MyString { public:   MyString(const char* s="")  throw();  ~MyString()                  throw();   MyString(const MyString& s) throw();   MyString& operator= (const MyString& s) throw();   friend ostream& operator<< (ostream& o, const MyString& s) throw(); protected:   char* s_; }; MyString::MyString(const char* s) throw() : s_(strdup(s)) { } MyString::~MyString() throw() { free(s_); } ostream& operator<< (ostream& o, const MyString& s) throw() { return o << s.s_; } int main() {   MyString s = "fred";   cout << s << "\n"; } 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net