reimplementing an interface in a derived class
kdevel
kdevel at vogtner.de
Sat Jan 5 00:16:11 UTC 2019
On Friday, 4 January 2019 at 20:21:56 UTC, Steven Schveighoffer
wrote:
>> missing in the source. But why is d a null reference in the
>> first place?
>
> Because when you dynamically cast one object or interface to
> another object or interface, and that result is not possible
> (if you remove ",D" from the example you quoted, then neither A
> nor B implement D), then the result is null.
I overlooked that Alex wrote
class A
and not
class A : D
which I came across in the examples in #10 and #11 of
https://dlang.org/spec/interface.html
and to which I referred to in my OP.
> https://dlang.org/spec/expression.html#cast_expressions
>
> See parts 2 and 3.
part 2
"Any casting of a class reference to a derived class reference
is done with a runtime check to make sure it really is a
downcast.
null is the result if it isn't."
Part 2 is about downcasting. Does that apply here? Due to the
omission
of ": D" in Alex' example the cast is not a cast "to a derived
class
reference" and hence this part does not apply. OTOH upcasting is
also
not covered by part 2 and seems to be legal:
part 2 at its face value:
```part2.d
import std.stdio;
class A {
void foo () { __FUNCTION__.writeln; }
}
class B : A {
override void foo () { __FUNCTION__.writeln; }
}
void main ()
{
auto x = new B;
auto u = cast (A) x;
typeof (u).stringof.writeln;
u.foo;
}
```
$ ./part2
A
part2.B.foo
More information about the Digitalmars-d-learn
mailing list