Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!ames!sun-barr!newstop!sun!basselope.Sun.COM!shiffman From: shiffman@basselope.Sun.COM (Hank Shiffman) Newsgroups: comp.lang.c++ Subject: Re: are 'friend's really necessary ?? Message-ID: <133042@sun.Eng.Sun.COM> Date: 17 Mar 90 06:14:32 GMT References: <169@pollux.kulcs.uucp> Sender: news@sun.Eng.Sun.COM Reply-To: shiffman@basselope.Eng.Sun.COM (Hank Shiffman) Organization: Sun Microsystems, Inc. Mt. View, Ca. Lines: 55 In article <169@pollux.kulcs.uucp> herman@kulcs.UUCP () 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++ ? > >Discussions with my colleagues didn't provide an example were friends were >really necessary. We could always find ways to implement our classes such >that the information hiding principle wasn't violated. We also couldn't >find a good example where data abstraction resulted in a serious loss of >efficiency (we could always find sensible inline functions that provided >fast access to the needed information). > >So, if you have an example that really proves the necessity of the friend >mechanism, please post it. After all, if there is no real necessity, the >mechanism is just an unnessary loophole in the language to defeat the >information hiding principle. > One case where friend functions are appropriate is where we may get to the function via typecasting. For example, let's say we implement a ratio class. We have a constructor for a ratio which takes zero, one or two integers. Now we want to implement subtraction. We might use a member function: ratio operator- (ratio&); or a friend function: friend ratio operator- (ratio&, ratio&); We choose to implement using a member function. Now consider the following piece of code: main () { ratio a(1,2), b, c; b = a - 5; c = 27 - b; } When compiling "b = a - 5", C++ won't find a function which subtracts an int from a ratio. However, there *is* a way to cast the int to a ratio (the ratio constructor), so the operator- member function can do the subtraction. Now consider "c = 27 - b". We can't use the member function, since C++ won't cast the recipient of the operator- "message". We *could* recode this as "c = -b + 27", assuming that we've defined the unary minus, but that's not fair to the user of our class. If we implement operator- as a friend function, then C++ can cast either one of the arguments to the ratio type and perform the subtraction. The requirement that the target of the member function be in the first position creates the need for friend functions. BTW, Dewhurst & Stark's Programming In C++ has a good explanation of this issue in relation to a complex number example.