ngo%tammy@HARVARD.HARVARD.EDU (Tom Ngo) (02/03/90)
C programmers are accustomed to expecting = to return the value assigned. However, in a few classes--for example, String, Integer and Rational-- operator == returns void. Is there a good reason for this? Could they be made to return String&, Integer& and Rational& *this without causing problems? Apologies if this has been brought up before... --Tom Ngo ngo@harvard.edu
dl@G.OSWEGO.EDU (Doug Lea) (02/03/90)
> > C programmers are accustomed to expecting = to return the value > assigned. However, in a few classes--for example, String, Integer > and Rational-- operator == returns void. Is there a good reason > for this? Could they be made to return String&, Integer& and > Rational& *this without causing problems? > The reason that X= (+=, -=, etc.) and = operators return void is to facilitate simple subclassing. While `utility' classes like String, Integer, etc., are not designed for extensive subclassing (since no members are virtual (which, in turn is motivated by efficiency considerations)), it is often convenient to create simple subclasses like class Line : public String. If you do this, then it is most desirable that inherited operators return void. Otherwise, unexpected type matches often occur. For example, if operator << (ostream&, Line&) were redefined for Line, but op += were inherited from String, and had return value String&, then { Line l; ...; cout << (l += "\n"); } would invoke op << (ostream&, String&), which is probably not what anyone would have in mind. This is avoided by having String::+= return void, making this usage illegal. Problems like this outweigh the syntactic convenience of supporting multiple right-associative uses of X= and =. A good rule of thumb about all this is that no non-virtual member functions should ever return *this by reference. (This rule is broken in a few places in libg++ for various reasons though.) -Doug