reimplementing an interface in a derived class

Steven Schveighoffer schveiguy at gmail.com
Fri Jan 4 20:21:56 UTC 2019


On 1/4/19 2:55 PM, kdevel wrote:
> On Friday, 4 January 2019 at 11:27:59 UTC, Alex wrote:
>> On Friday, 4 January 2019 at 09:58:59 UTC, bauss wrote:
> 
> [...]
> 
>> As for the OP, I think here the usefulness of ", D" should be visible:
> 
> [...]
> 
>> class B : A, D
>> {
>>     override int foo() { return 2; }
>> }
> 
> [...]
> 
>>     D d = cast(D) b;
>>     assert(d.foo == 2);             // returns 2
> 
> If I remove the ", D" the program segfaults in this line:
> 
> Program received signal SIGSEGV, Segmentation fault.
> 0x000000000042c184 in D main () at ggg.d:26
> 26        d.foo();
> (gdb) p d
> $1 = (ggg.D *) 0x0
> 
> There is clearly an
> 
>     assert (d);
> 
> 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.

https://dlang.org/spec/expression.html#cast_expressions

See parts 2 and 3.

-Steve


More information about the Digitalmars-d-learn mailing list