Thread View: gnu.g++.lib.bug
2 messages
2 total messages
Started by Tom Ngo
Sat, 03 Feb 1990 04:42
Should "operator =" be made to return *this, by convention?
Author: Tom Ngo
Date: Sat, 03 Feb 1990 04:42
Date: Sat, 03 Feb 1990 04:42
11 lines
851 bytes
851 bytes
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
Should "operator =" be made to return *this, by convention?
Author: Doug Lea
Date: Sat, 03 Feb 1990 12:03
Date: Sat, 03 Feb 1990 12:03
31 lines
2020 bytes
2020 bytes
>
> 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
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads