overiding mutable methods in immutable classes
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Nov 21 21:52:44 PST 2014
On 11/21/14 7:24 PM, Eric wrote:
>
>
>
> immutable class X
> {
> private int x;
> this(int x) { this.x = x; }
> ...
> override size_t toHash(); // error: can't override mutable method
> }
>
> Since toHash() cannot be overridden in an immutable class,
> is there a work-around?
Kind of, but I don't think it's good that it works. Note that you
shouldn't be able to call mutable toHash on an immutable object, but the
runtime bludgeons it through:
class X
{
override size_t toHash() {return x;}
immutable:
... // everything else
}
This is equivalent to saying you have an immutable class, but just that
one method is mutable. D lacks a mechanism to say something is mutable.
> In other words,
>
> immutable X x1 = new immutable X(5);
> immutable X x2 = new immutable X(5);
>
> I would like for x1.toHash() to equal x2.toHash(),
> but this is not the case because toHash() cannot be overridden.
> Note also that (x1 != x2) even though they should be equal (I think...)
> Is this a bug or a feature?
Classes are always references. This means you are comparing the class
reference x1 to the class reference x2, and they point at different
pieces of memory.
You can override opEquals to define how to compare them, if you want !=
to work. I will note that opEquals *and* toHash must be overridden to
work with AAs.
-Steve
More information about the Digitalmars-d-learn
mailing list