Why is this allowed? Inheritance variable shadowing

mw mingwu at gmail.com
Wed May 26 21:50:21 UTC 2021


On Wednesday, 26 May 2021 at 18:58:47 UTC, JN wrote:
> On Tuesday, 13 August 2019 at 04:40:53 UTC, Chris Katko wrote:
>> You can drop this straight into run.dlang.io:
>>
>> import std.stdio;
>>
>> class base{ float x=1;}
>> class child : base {float x=2;} //shadows base variable!
>>
>> void main()
>> {
>>
>>     base []array;
>>     child c = new child;
>>     array ~= c;
>>
>>     writeln(c.x); //=2
>>     writeln(array[0].x); //=1  //uses BASE's interface, yes,
>>     //but why does the CHILD instance one exist at all?
>> }
>>
>
> Just got bitten by this. When copy pasting code of a bigger 
> class, it's easy to miss the redefinition of variable.
>
> Is there any viable usecase for this behavior? I am not buying 
> the "C++ does it and it's legal there" argument. There's a 
> reason most serious C++ projects use static analysis tools 
> anyway. D should be better and protect against dangerous code 
> by default. I think a warning in this case would be warranted.

Agree, at least a warning message, a PR someone?



More information about the Digitalmars-d-learn mailing list