[Bug 191] New: Cannot refer to member variable in default value	for method parameter
    Jarrett Billingsley 
    kb3ctd2 at yahoo.com
       
    Sun Jun 11 12:12:44 PDT 2006
    
    
  
"Deewiant" <deewiant.doesnotlike.spam at gmail.com> wrote in message 
news:e6hp54$a2d$1 at digitaldaemon.com...
> For what it's worth, I don't see any sense in this restriction - how is a
> class's member different from any other variable in this situation?
Oh, wow, I didn't know that it allowed you to do this with other kinds of 
variables.  I always thought that the default parameter initializer had to 
evaluate to a constant!
> Especially
> since the workaround is so simple, and isn't that all that default 
> parameters
> are meant to do - overload the method into a form which takes one less 
> parameter
> and passes the default value to the original?
Well, as far as I know, that's not how the compiler implements it.  It just 
keeps one copy of the function, and when it comes across a call that doesn't 
have all the parameters, it rewrites the function call so that the unwritten 
parameters use the parameter initializer.  So there's no actual overloading 
going on.
> They don't have to implement it
> that way, but that's how I see the semantics of it.
That might be the problem - depending on whether or not the default argument 
was a member variable, it might end up adding complexity to the default 
argument mechanism, since the value of a local variable can't really be 
determined until _after_ the function has been called with a 'this' 
reference.  It would be like trying to do something like:
void func(int[] x, int y = x[5])
Since x[5] can't be determined until after func() has been called, it would 
have to have multiple code paths for func; one which would be for taking a 
y, and one which would determine y from the x argument.
Though it could possibly be added into the current mechanism, if you had a 
class like:
class A
{
    int x;
    void func(int y = x)
    {
        writefln(y);
    }
}
Then if you called func:
A a = new A;
a.func();
The compiler would know that the default initializer for the first argument 
is the member variable x, and would then rewrite the call as:
a.func(a.x);
Possible, but kind of complicated.
Overloading a function to implement the default parameter with a member 
variable as the initializer seems like a simple enough workaround until 
(if?) this is fixed.  I agree that it should be possible for consistency 
with the ability to use other variables as default argument initializers, 
but I don't know how many extra levels of complexity it adds. 
    
    
More information about the Digitalmars-d-bugs
mailing list