Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!snorkelwacker.mit.edu!bloom-beacon!eru!hagbard!sunic!mcsun!ukc!mucs!jk From: jk@cs.man.ac.uk (John Kewley ICL) Newsgroups: comp.lang.c++ Subject: Re: friend operator +(l,r) vs. operator +(r) Message-ID: <1939@m1.cs.man.ac.uk> Date: 23 Nov 90 10:00:34 GMT References: <11759@hubcap.clemson.edu> Sender: news@cs.man.ac.uk Reply-To: jk@cs.man.ac.uk (John Kewley ICL) Organization: Department of Computer Science, University of Manchester UK Lines: 56 In article <11759@hubcap.clemson.edu> grimlok@hubcap.clemson.edu (Mike Percy) writes: >I've tried and tried to get a handle on this question from various >sources, but haven't been enlightened... > >What semantic/operational and/or stylistic differences are there >between these two definitions? > >class foo { >... >public: > foo& operator +(foo& rhs); >} > >and > >class foo { >... >public: > friend foo& operator +(foo& lhs, foo&rhs); >} > >I must be missing something, because to me these effectively are the >same thing, but the first can operate on this. > If needed, the first definition can be a private or protected function. This is not possible with a friend. Implicit type coersions are not permitted on the LHS of the non-friend version. e.g. 1 + x is not allowed for the member but would be valid for the friend, assuming a coersion from int -> foo. Note that operator= (and [], (), ->) must be defined using the first method. The second method should be used when there is a need for the parameters to be ordered with the object as the second parameter - operator<< usually needs to be defined using the friend syntax when it is overloaded with the output function. A friend can also be used for a function to operate on two objects of different classes. It would be declared as friend within each class. If the function + is defined in C (or another language), the friend version would be neccessary. In the non-operator case, friends have a different syntax (less object-oriented) so functions such as print can be called as print(foobar) rather than foobar.print(). All this being said it is often unclear whether to declare a function as a friend or a member. Where there is no over-riding need I prefer members. -- J.K. John M. Kewley, ICL, Wenlock Way, West Gorton, Manchester. M12 5DR Tel: (+44) 61 223 1301 X2138 Email: jk@r6.cs.man.ac.uk / jk@nw.stl.stc.co.uk