Should this always work?

Mike Parker aldacron at gmail.com
Sat May 1 10:08:17 UTC 2021


On Saturday, 1 May 2021 at 08:03:45 UTC, frame wrote:

>
> In case of a void* to abstract class casting, I assume the 
> compiler just inserts the right vtable, so this cast is 
> unproblematic - or is there also a pitfall?

I wouldn't expect there to be any consideration of vtables 
whatsoever. The compiler just reinterprets the pointer as a class 
reference, whether you're casting it to the original class or a 
superclass type. I mean, all of the functions available to the 
class are already in the vtable. There's no need to insert 
anything.

Whether you're getting at a class instance through a subclass (C) 
reference or a superclass (A) reference, abstract or not, it's 
still only a single instance located at a single address.

```d
import std.stdio;

abstract class A {
     void doIt();
}

class C : A {
     override void doIt() { writeln("Doing it"); }
}

void main()
{
     C c = new C;
     void* pc = cast(void*)c;
     A a = cast(A)pc;
     a.doIt();
}
```

So the pitfall is the same: when you're casting class references 
to and from pointers, it's up to you to ensure that the type you 
cast to is appropriate. You get no help from the compiler here.



More information about the Digitalmars-d-learn mailing list