digitalmars.D.learn - Interface wierdness
- Ruby The Roobster (38/38) May 06 2022 Define an interface that has a function that returns an object of
- Ruby The Roobster (2/5) May 06 2022 Nevermind. I was being stupid and made a naming error.
- Salih Dincer (33/34) May 06 2022 What version compiler are you using? I've tried it in two
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?
May 06 2022
On Saturday, 7 May 2022 at 00:48:20 UTC, Ruby The Roobster wrote:Define an interface that has a function that returns an object of the same type: ..Nevermind. I was being stupid and made a naming error.
May 06 2022
On Saturday, 7 May 2022 at 00:48:20 UTC, Ruby The Roobster wrote:Why does this happen and how to fix it?What version compiler are you using? I've tried it in two different versions (one is the newest), it works: ```d import std; interface I { I foo(); } class M : I { this(int i) { this.i = i; } M foo() { return new M(42); } int i; } void main() { M m = new M(3); m.i.writeln("(m.i)"); M c = m.foo(); c.i.writeln("(c.i)"); }/*Printouts: 3(m.i) 42(c.i) Process finished. */ ```
May 06 2022









Ruby The Roobster <michaeleverestc79 gmail.com> 