Constructor params with same name as members

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 22 23:37:00 PDT 2014


On Thursday, October 23, 2014 11:47:04 Shriramana Sharma via 
Digitalmars-d-learn wrote:
> Oh OK here it is:
> http://dlang.org/deprecate.html#Variable%20shadowing%20inside%20functions
>
> But it says "it is an error to use the feature" by 2.061 and 
> I'm using
> 2.066!
>
> Doesn't the scope of that deprecation cover struct members too? 
> In
> general it should be like "variables in inner scopes should not 
> shadow
> those in outer scopes" irrespective of what the scopes are, 
> right?
>
> Of course, for clarity we could add "except when the inner 
> scope is a
> separate namespace", so it is made clear that enum/struct/class
> members do not shadow outer variables...

Shadowing is only illegal when you're dealing with local 
variables both declared within the same function with one in an 
inner scope. It's perfectly legal when one variable is a local 
variable and the other is a member variable, class/struct 
variable, or module-level variable. Having a parameter shadow a 
member variable is perfectly okay, because you can still 
reference the member variable via the invisible this parameter.

Questions like this have come up and been discussed before, but 
using the same parameter names as member variable names for 
constructors is such a common practice that there would be quite 
a bit of screaming if we didn't allow it. It's not going away, 
and personally, I'd be very annoyed if it did. It's wonderfully 
clear when the parameter name has the same name as the member 
variable that it's going to initialize, and I'd hate to have to 
come up with different parameter names just because someone was 
worried about someone being foolish enough to do

x = x;

which is so obviously wrong that I don't know how much of anyone 
could make that mistake. But simply making it illegal to assign a 
variable to itself would solve that problem, and that arguably 
should be done, since it's a essentially a no-op.

Regardless, a lot of people solve it by simply tagging their 
member variables in some manner to indicate that they're member 
variables and not local variables - e.g. _x instead of x.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list