Fields with the same name not causing a warning?

Basile B. b2.temp at gmx.com
Fri Nov 16 17:08:00 UTC 2018


On Friday, 16 November 2018 at 15:59:14 UTC, Vinay Sajip wrote:
> This code should IMO give at least a warning, but it doesn't:
>
> abstract class A {
>     int kind;
> }
>
> class B : A {
>     int kind;
>
>     this(int k) {
>         kind = k;
>     }
> }
>
> In my actual code, the declaration of field "kind" in B was 
> left in accidentally. Surprisingly, however, no warning was 
> emitted when I compiled this, leading to B having two fields 
> called kind which are distinct from one another. The complete 
> program
>
> import std.stdio;
>
> abstract class A {
>     int kind;
> }
>
> class B : A {
>     int kind;
>
>     this(int k) {
>         kind = k;
>     }
> }
>
> void main()
> {
>     auto b = new B(4);
>     A a = b;
>
>     writeln(b.kind);
>     writeln(a.kind);
> }
>
> prints
>
> 4
> 0
>
> Given that this is the kind of thing that is easily done, 
> surely the default behaviour should be for the compiler to emit 
> at least a warning that field "kind" is ambiguous in B? This 
> behaviour occurs even when the field is declared as "public" or 
> "protected" in both classes. What am I missing?

When you re declare with the same name in a sub class each 
generation has its own variable. To distinguish you can use the 
type for which you want "kind":

     writeln(b.A.kind); // the one from A
     writeln(b.B.kind); // the one from B

I agree that this is almost a case of shadowing but i don't know 
the exact rationale for allowing this.


More information about the Digitalmars-d-learn mailing list