[Bug 191] New: Cannot refer to member variable in default value for method parameter

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon Jun 12 09:33:21 PDT 2006


BCS skrev:
> Deewiant wrote:
>> Jarrett Billingsley wrote:
>>
>>> Is this even in the spec?  I had no idea you were supposed to be 
>>> allowed to use members as default parameters.
>>
>>
>> All I can find about default parameters in the spec is at the 
>> "Functions" page,
>> where they pop out of the blue in the phrase "A function parameter's 
>> default
>> value is not inherited", which is all that's said about them. The 
>> changelog for
>> DMD 0.92 also says "Added default arguments to function parameters. 
>> Semantics
>> are like C++." but that's it.
> [...]
> 
> Is this correct behavior? If it is it needs to be documeted better.
> 
> <code>
> import std.stdio;
> 
> class C        { int foo(int x = 1){return x;} }
> class D:C    { int foo(int x = 2){return x;} }
> 
> 
> void main()
> {
>     C c = new D;
>     D d = cast(D)c;
> 
>     writef(c.foo,\n);    // prints 1 (?)
>     writef(d.foo,\n);    // prints 2
> }
> </code>

I guess this is the intended behavior. The default argument is evaluated 
at call site and passed to the function. main() calling c.foo has no way 
of knowing (at compile time) what derived class instance c may hold 
(there is no vtbl for default arguments).

I see how this can lead to hard to find bugs. I.e. if the default 
argument is changed in the base class, but not in a (maybe independently 
developed) derived class. It may be better if D inherited default values 
and forbade them to be redefined in derived classes.

/Oskar



More information about the Digitalmars-d-bugs mailing list