A fresh look at comparisons
Janice Caron
caron800 at googlemail.com
Mon Apr 14 07:43:53 PDT 2008
On 14/04/2008, Henning Hasemann <hhasemann at web.de> wrote:
> Depending on what type of code you write you don't want every member
> automagically being compared. In some game code I write curretly there
> are for example lots of members which would not apply for comparsion.
> I think its more a matter of taste if members should be compared by
> default or not.
Yes, all we're talking about here is a sensible /default/. The fact
that you can override the default, by supplying your own function,
means that, in some sense, it almost doesn't matter what the default
is, because if it's not what you want, then you can override it. But
even so - it's nice to get the default covering the most common cases.
To me, it seems sensible that the default implementation should be to
compare all members (including super). This means that if a subclass
adds new members, then by default, a test for subclass equality will
be true iff (1) the superclass compares as equal, and (2) the new
members also compare as equal.
The inheritance mechanism (which is what we have now, thanks to the
fact that opEquals() is a regular function), means that if a subclass
adds new members, then by default, a test for subclass equality will
be true iff the superclass compares as equal. All new members will be
ignored.
> But with throwing away inheritance you throw away all the
> considerations you made in A which properties identify two equal
> objects. Is that really what you want?
It's not "throwing away", because the default implementation would
include a test for superclass equality. ("super" is a member just like
any other). So if B extends A, and also adds two member variables x
and y, then the test (b1 == b2) would be evaluated as:
// Your scheme
b1.super == b2.super
or
// My scheme
b1.super == b2.super
&& b1.x == b2.x
&& b1.y == b2.y
So we don't lose inheritance - we just gain extra tests. Of course, if
you don't /want/ those extra tests, then you would have to override
the default - such is the nature of defaults - by doing something like
class B : A
{
int x,y;
is(this == that)
{
return super == that.super;
// x and y are now ignored
}
}
> So enough for the war for now ;)
> I really like your idea just to make myself clear.
Thanks. And there was never any question of warfare! :-)
More information about the Digitalmars-d
mailing list