reimplementing an interface in a derived class

Alex sascha.orlov at gmail.com
Fri Jan 4 11:27:59 UTC 2019


On Friday, 4 January 2019 at 09:58:59 UTC, bauss wrote:
> On Friday, 4 January 2019 at 09:53:18 UTC, Alex wrote:
>> I assume the move method of an Animal is not abstract, and 
>> therefore I supposed, casting to this type explicitly should 
>> restore this very non-abstract behavior. But this is not the 
>> case.
>> And the final/virtual thing above explains this to some 
>> extent, too... I think...
>
> A cast is only a way to tell the compiler the signature of a 
> type.
>
> In most cases it actually does nothing at runtime and is just a 
> way to help the compiler.
>
> Ex.
> auto b = new B;
> auto a = cast(A)b;
>
> Will just tell the compiler that all usage of a will be 
> restricted to the signature of A.
> It doesn't tell the compiler that all usage of a should be the 
> same as A.
>
> At runtime it would actually just be:
> auto b = new B;
> auto a = b; //*

* The last line is thought to be restricted to the signature of 
A, but the behavior of B.

Yeah... I think this is a matter of habituation. I assumed 
casting is something more powerful and overcomes the virtuality 
of functions if their body exists. But its the other way round. 
Thanks for the clarification.

As for the OP, I think here the usefulness of ", D" should be 
visible:

´´´
interface D
{
     int foo();
     final int fun(){ return 42; }
}

class A
{
     //size_t dummy;
     int foo() { return 1; }
     int fun() { return 72; }
}

class B : A, D
{
     override int foo() { return 2; }
}

void main()
{
     B b = new B();
     assert(b.foo == 2);             // returns 2
     assert(b.fun == 72);            // fun returns 72, as defined 
in A

     D d = cast(D) b;
     assert(d.foo == 2);             // returns 2
     assert(d.fun == 42);            // fun returns 42, as defined 
in D

     A a = cast(A) b;
     assert(a.foo == 2);             // returns 2, as it remains B
     assert(a.fun == 72);            // fun returns 72, as defined 
in A

     D d2 = cast(D) a;
     assert(d2.foo == 2);            // returns 2, as it remains B
     assert(d2.fun == 42);           // fun returns 42, as defined 
in D

     A a2 = new A();
     assert(a2.foo == 1);            // returns 1, as defined in A
     assert(a2.fun == 72);           // returns 72, as defined in A
     assert((cast(D) a2) is null);   // not castable to D
}
´´´


More information about the Digitalmars-d-learn mailing list