ryan27968
ryan27968

Reputation: 477

Comparison operator overloading for class in D?

I am currently learning D and struggling to understand how operator overloading could work for a class? Overriding opCmp makes sense and works correctly for a struct, but for a class it requires taking the right hand side as a Object instead of as my type.

This means I can't access any members to do a comparison. What's the point in the overload then? Am I missing something?

Upvotes: 3

Views: 161

Answers (1)

BioTronic
BioTronic

Reputation: 2289

Sure you can access your members:

class MyClass {
    int member;
    override int opCmp(Object other) {
        if (auto mcOther = cast(MyClass)other) {
            // other, and thus mcOther, is an instance of MyClass.
            // So we can access its members normally:
            return member < mcOther.member ? -1
                 : member > mcOther.member ?  1
                 :                            0;
        } else {
            // other is not a MyClass, so we give up:
            assert(0, "Can't compare MyClass with just anything!");
        }
    }
}

The reason opCmp for classes takes Object as a parameter is it's being introduced in the Object class, from which every D class derives. Introducing opCmp there was a sensible choice back in the day, but less so now. However, since we don't want to break every piece of D code out there that uses opCmp (and opEquals, toHash and toString) with classes, we're kinda stuck with that choice.

Upvotes: 2

Related Questions