reimplementing an interface in a derived class
Steven Schveighoffer
schveiguy at gmail.com
Mon Jan 7 15:48:35 UTC 2019
On 1/4/19 7:16 PM, kdevel wrote:
> 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?
Yes. If the requested interface or class isn't a base class, or a base
interface, then a downcast must be involved. Essentially the downcast is
a runtime check to see if this class instance actually is a derived one,
or a derived class implements the specified interface. D does not have
multiple inheritance.
> 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.
Of course it applies :) The fact that the class is not an instance of D
in a derived class means that it returns null. The spec statement could
be worded better.
> OTOH upcasting is also
> not covered by part 2 and seems to be legal:
Upcasting is trivial, and the compiler will not even spend time doing a
runtime check, it knows how to do this at compile time. It doesn't even
require a cast.
Just like casting a short to an int doesn't require a cast, but you are
free to put one in if you like.
-Steve
More information about the Digitalmars-d-learn
mailing list