Why are opEquals/opCmp arguments not in or const for Objects?

Stewart Gordon smjg_1998 at yahoo.com
Tue Mar 19 13:51:28 PDT 2013


On 19/03/2013 05:38, Jonathan M Davis wrote:
<snip>
> Well, IIRC, if when you override a function, and you give it a
> different parameter type, it's a new overload rather than actually
> overriding anything (even if the type of the parameter in the derived
> type's function is a derived type of the type of the parameter in the
> base class' function).

I've just been reminding myself of what
http://dlang.org/hijack.html
says about this.  As it turns out, they are indeed separate overloads, 
albeit protected by hiding the base class's version from derived class 
references.

> So, if you don't use a common type for the parameter, you'll run into
> overload conflicts regardless. So, while you _could_ use something
> other than Object, you could run into overload conflicts if you do.
> That can be gotten around by aliasing base class functions into the
> scope of the derived class (though that may cause derived types to be
> compared as base types if they're referred to via references to the
> base type, so that may no be a good idea) or by creating overloads
> for comparing every base class, but it's arguably easier to just
> accept Object and cast - or accept whatever the base type is which
> first introduces opEquals into the hierarchy.
<snip>

I've always defined both opEquals(Object) and opEquals(MyClass), and 
likewise for opCmp where applicable, and made the Object version call 
the class-specific version.  This way, the overhead of a cast is avoided 
in the case where you're comparing two objects through references of the 
specific class type.

Of course, once these are removed from Object, it will just be a case of 
removing the Object versions of these methods from my class.

But the question still remains: How do we implement this change without 
causing mass disruption?  It might be the case that programmers just 
need to remove opEquals(Object) and opCmp(Object) from their classes, 
and remove the override attribute from toHash and toString (and declare 
them const as appropriate).  But there will be a lot of libraries to 
convert, and it will take time for them all to be converted.

Stewart.


More information about the Digitalmars-d mailing list