Cast class reference to pointer of another class?
ag0aep6g
anonymous at example.com
Sat May 29 22:26:48 UTC 2021
On Saturday, 29 May 2021 at 21:01:14 UTC, JN wrote:
> this code compiles. Why? What is even the result in "f" in this
> case?
On Saturday, 29 May 2021 at 21:03:12 UTC, JN wrote:
> fixed formatting:
>
> ```d
> struct Foo
> {
> }
>
> class Bar
> {
> }
>
> void main()
> {
> Bar b = new Bar();
> Foo* f = cast(Foo*)b;
> }
> ```
You're writing @system code, so dangerous casts are allowed. It's
no surprise that the code compiles. If you want to be safeguarded
against such things, use @safe.
The result is a class object being reinterpreted as a struct
object. Usually, that's just nonsense. But it might be useful for
some expert who wants to tinker with the object's internals.
More information about the Digitalmars-d-learn
mailing list