Constructor Parameter vs Member Variable

Christopher Winter christopher.winter at ahrefs.com
Tue Dec 5 02:41:51 UTC 2023


If you have a struct member variable named `a` and a constructor 
for that struct that takes a parameter named `a`, it isn't 
obvious what the usage of `a` in the body refers to.

```
import std;

struct F
{
     int a;
     int b;

     this(double a)
     {
         writeln(a);
         a = a;
     }
}

void main()
{
     scope f = F(15);

     writeln(f.a);
}
```

The behavior is extremely unintutive, and arguably broken, in 
that it a) compiles and b) will print 15 on the first line and 0 
on the second line. Additionally, if you rename the constructor 
parameter to be `c`, then it fails to compile (because you can't 
assign a double to an int).

Is there a way to have the compiler warn or error in this 
situation? Or in general does anyone know ways to avoid the 
ambiguity, other than just being careful with names?


More information about the Digitalmars-d mailing list