Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!mcdchg!tellab5!balr!clrcom!rmartin From: rmartin@clear.com (Bob Martin) Newsgroups: comp.lang.c++ Subject: Re: friend operator +(l,r) vs. operator +(r) Message-ID: <1990Nov22.230835.26713@clear.com> Date: 22 Nov 90 23:08:35 GMT References: <11759@hubcap.clemson.edu> <1990Nov21.053431.22340@actrix.co.nz> Organization: Clear Communications, Inc. Lines: 54 In article <1990Nov21.053431.22340@actrix.co.nz> Bruce.Hoult@bbs.actrix.gen.nz writes: >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. > > >The important difference is that the friend version allows implicit >conversions to be made on both the left hand and right hand arguments >to +, wheras the member function version allows implicit conversions >on only the RH argument. Let me elaborate on this a bit. Let us say that you have created a constructor as follows: foo::foo(int). This tells the compiler that it is allowable to convert an int into a foo. Now lets say that you use the following code: foo fa,fb; int ia; ... fb=ia+fa; // adding an int to a foo. If you use the foo::operator+(foo&) method, then the above statement will produce a compiler error since foo::operator+(foo&) requires that the left hand side of the + operator must be a foo. But if you use the friend operator+(foo&,foo&) then the compiler knows how to convert ia into a foo before 'adding' fa. -- +-Robert C. Martin-----+:RRR:::CCC:M:::::M:| Nobody is responsible for | | rmartin@clear.com |:R::R:C::::M:M:M:M:| my words but me. I want | | uunet!clrcom!rmartin |:RRR::C::::M::M::M:| all the credit, and all | +----------------------+:R::R::CCC:M:::::M:| the blame. So there. |