Outer class reference oddity?

Paul Backus snarwin at gmail.com
Tue Aug 20 17:11:01 UTC 2024


On Tuesday, 20 August 2024 at 08:48:33 UTC, Manu wrote:
> Another thing I've never tried to use in D before; an outer 
> class reference! As usual, I try to use a thing and it doesn't 
> work...
>
> Here's a situation:
>
> import std.stdio;
>
> class Outer1 {
>     int value1 = 100;
>
>     class Inner1 {
>         void print() {
>             writeln("value1 from Outer1: ", value1);
>         }
>     }
>
>     Inner1 make() { return new Inner1; }
> }
>
> class Outer2 : Outer1 {
>     int value2 = 200;
>
>     class Inner2 : Outer1.Inner1 {
>         override void print() {
>             writeln("value1 from Outer1: ", value1); // <- no 
> problem!
>             writeln("value2 from Outer2: ", value2); // error : 
> accessing
> non-static variable `value2` requires an instance of `Outer2`
>         }
>     }
>
>     override Inner2 make() { return new Inner2; }
> }

It works if I change the erroring line to access value2 through 
the outer pointer [1] explicitly:

     writeln("value2 from Outer2: ", this.outer.value2); // ok

So yes, this is definitely a bug.

[1]: https://dlang.org/spec/class.html#outer-property


More information about the Digitalmars-d mailing list