Constructor Parameter vs Member Variable

DrDread DrDread at cheese.com
Tue Dec 5 15:52:08 UTC 2023


On Tuesday, 5 December 2023 at 14:23:26 UTC, Christopher Winter 
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).
>
>> The solution to this is to use the this reference when there's 
>> any ambiguity.
>
> Yeah, I suppose for me always using `this` is probably the best 
> way to avoid any ambiguity.

you can't really prevent parameter names to be the same as member 
var names, or else you'll break metaprogramming. so sadly there 
is no way to solve this ambiguity except writing this. if you 
want to access a member.


More information about the Digitalmars-d mailing list