Constructor Parameter vs Member Variable

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Dec 5 16:30:42 UTC 2023


On Tuesday, December 5, 2023 7:23:26 AM MST Christopher Winter via 
Digitalmars-d wrote:
> On Tuesday, 5 December 2023 at 04:31:28 UTC, Jonathan M Davis
>
> wrote:
> > This behavior is actually extremely common in OO programming
> > languages.
>
> Yeah, I understand that it is variable shadowing, but this nearly
> identical situation is rejected by the compiler:
>
> ```
> void fun(double a)
> {
>      int a = cast(int) a; <-- Error: variable `a` is shadowing
> variable `main.fun.a`
> }
> ```
>
> I don't really understand why these scenarios would be treated
> differently by the compiler (I would even argue that my intention
> here is more explicit vs in the constructor, but not everyone may
> agree with that).

A big difference is that if you shadow a local variable with another local
variable, you don't have any way to differentiate between them. So, when you
shadow a local variable, that variable becomes inaccessible within that
section of code, whereas with a member variable, you can distinguish with
the this reference, and with a variable at module scope, you can
differentiate a leading dot. So, the error prevents you from making
variables inaccessible, whereas there is no need for such an error when
shadowing non-local variables.

Also, shadowing non-local variables is sometimes hard to avoid, whereas with
a local variable, you're in control of all of the names within the function,
and it's pretty rare that there would even arguably be a good reason for
shadowing a local variable. If a programmer does it, it's almost certainly a
mistake, and they're going to want the compiler to tell them about it.

On the other hand, a ton of programmers very much want to shadow member
variables in constructors. They want the parameter names to match the names
of the variables for documentation purposes, and they're used to dealing
with that shadowing, so they don't consider it a big deal. It's rarely a
problem in practice, and it's the kind of bug that's found very quickly in
testing if you make a mistake.

- Jonathan M Davis





More information about the Digitalmars-d mailing list