toString() through interface

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Apr 19 18:15:58 PDT 2014


David Held:

> class Baz
> {
>     override string toString() pure const
>     { return cast(Object)(foo).toString(); }
>
>     Foo foo;
> }
>
> This really makes the compiler go bonkers:
>
> src\Bug.d(11): Error: pure nested function 'toString' cannot 
> access mutable data 'foo'
> src\Bug.d(11): Error: pure nested function 'toString' cannot 
> access mutable data 'foo'
> src\Bug.d(11): Error: no property 'toString' for type 'Bug.Foo'
> src\Bug.d(11): Error: pure nested function 'toString' cannot 
> access mutable data 'foo'
> src\Bug.d(11): Error: need 'this' for 'foo' of type 'Bug.Foo'
>
> Apparently, DMD features "high-availability error reporting", 
> because the first message might not be received by the 
> programmer, so it writes it again, then gives you a different 
> message, and writes it one more time, just in case there was a 
> communication error or some other fault preventing you from 
> receiving this important message about access to 'foo'.

Your code is probably wrong, but those error messages seem too 
many. So I suggest you to open a little bug report, asking for 
less error messages :-)


> Is there a rational explanation for all this behavior??

Try also:

     override string toString() const {
         return (cast(Object)foo).toString();
     }


You still have to understand some things about the D objects and 
interfaces, their standard methods, and what const and purity do 
in D.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list