Newsgroups: comp.lang.c++ Path: utzoo!censor!geac!alias!earth!rae From: Reid Ellis Subject: "foo operator+()" vs "foo& operator+()" [WAS friend vs member operator+()] Message-ID: Sender: Reid Ellis Reply-To: Reid Ellis Organization: Alias Research, Inc. Toronto ON Canada References: <11759@hubcap.clemson.edu> <1990Nov21.140621.4229@ssd.kodak.com> <11782@hubcap.clemson.edu> <1990Nov22.001208.26092@athena.mit.edu> Date: 22 Nov 90 19:06:18 GMT ahodgson@hstbme.mit.edu (Antony Hodgson) writes: >Just a warning that the use of the expression: > > foo& operator + ( foo& f ) >or > friend foo& operator + ( foo& f1, foo& f2 ) > >will almost invariably lead to a run-time error. ... > ... It's much better to define the operator as > > foo operator+(foo& f) > >and let the system deal with deallocating it when it goes out of scope. If the object if large, it is sometimes desirable to maintain a static instance within the operator method and return a reference. e.g.: foo & foo::operator+=(const foo &f) { ... } foo & foo::operator+(const foo &f) { static foo sf; sf = *this; return sf += f; } This is a variation on the standard "use the stack" method of operator+(). The only way to get "caught" using this is if you hold the return value in a reference, as in: foo &rf = foo1 + foo2; I consider this poor form myself. If you had defined the add method as "foo foo::operator+(..)" then you would be creating a reference to a temporary. Reid -- Reid Ellis 176 Brookbanks Drive, Toronto ON, M3A 2T5 Canada rae@gpu.utcs.toronto.edu || rae%alias@csri.toronto.edu CDA0610@applelink.apple.com || +1 416 446 1644