Why is this allowed? Inheritance variable shadowing
JN
666total at wp.pl
Wed May 26 18:58:47 UTC 2021
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.
More information about the Digitalmars-d-learn
mailing list