Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!cs.utexas.edu!tut.cis.ohio-state.edu!att!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: are 'friend's really necessary ?? Message-ID: <10589@alice.UUCP> Date: 17 Mar 90 14:25:57 GMT References: <169@pollux.kulcs.uucp> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 53 In article <169@pollux.kulcs.uucp>, herman@kulcs.uucp (Herman Moons) writes: > I don't know whether this question appeared earlier on the net. > Are there any *good* reasons for having the friend concept in C++ ? Sure. One of the most common is when you're writing several interrelated classes. > The example given in Lippman's book: > class Screen; > Screen myScreen; > cout << myScreen; // friend needed to implement this > does not seem convincing. The friend mechanism is used in this case to > circumvent a bad design choice. It is at least as bad a design choice to require myScreen >>= cout; but to allow cout << "hello world\n"; The inconsistent syntax does nothing to help program clarity. I will admit, however that it is possible to write this particular example without friends: class MyScreen { // ... public: ostream& print(ostream& o) { // print *this on o return o; }; }; ostream& operator<<(ostream& o, const Screen& s) { return s.print(o); } The operator<< defined here does not need to be a friend of MyScreen as long as the print function is public. Of course you may not want the print function to be public. After all, there's no overriding reason to fix it as part of the interfact to MyScreen. But if you make it private, then operator<< must be a friend of MyScreen... -- --Andrew Koenig ark@europa.att.com