Should this always work?

frame frame86 at live.com
Sat May 1 04:55:10 UTC 2021


I always thought as long as an object implements an interface, it 
should be able to cast it from a void* if it really points to a 
supporting object.

I have the similar structure:


```d
interface AI {
     string doSomething();
}

template S() {
     void foo() {

     }
}

abstract class A : AI {
     string doSomething() {
         return "Hello, World";
     }
}

class B : A {
     mixin S;

     void other() {

     }
}

auto b = new B;
auto p = cast(void*) b;
auto c = cast(AI) p;

c.doSomething();
```

But in my code with the real object, this generates a RangeError, 
AcccesError, memory garbage:
```d
auto b = new B;
auto p = cast(void*) b;
auto c = cast(AI) p; // AI with corrupt data

c.doSomething(); // error
```

But this works:
```d
auto b = new B;
auto p = cast(void*) b;
auto c = cast(A) p; // A with correct data

c.doSomething(); // no error
```

If the runtime could not successfully cast it to AI, it should 
return null. Am I wrong here?


More information about the Digitalmars-d-learn mailing list