Interface wierdness

Ruby The Roobster michaeleverestc79 at gmail.com
Sat May 7 00:48:20 UTC 2022


Define an interface that has a function that returns an object of 
the same type:

```d
interface I
{
     I foo();
}
```

Now define a class that inherits that interface:

```d
class M : I
{
     this(int i)
     {
         this.i = i;
     }
     M foo()
     {
         return new M(42);
     }
     int i;
}
```

Given this example, the following main function fails to compile:

```d
void main()
{
     M m = new M(3);
     M c = m.foo();
     import std.stdio;
     writeln(c.i);
}
```

The error message is the following:

```
Error: need `this` for `foo` of type `M()`
```

Why does this happen and how to fix it?


More information about the Digitalmars-d-learn mailing list