www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Cast class reference to pointer of another class?

reply JN <666total wp.pl> writes:
```struct Foo
{
}

class Bar
{
}

void main()
{
     Bar b = new Bar();
     Foo* f = cast(Foo*)b;
}```

this code compiles. Why? What is even the result in "f" in this 
case?
May 29 2021
parent reply JN <666total wp.pl> writes:
fixed formatting:

```d
struct Foo
{
}

class Bar
{
}

void main()
{
     Bar b = new Bar();
     Foo* f = cast(Foo*)b;
}
```
May 29 2021
parent reply ag0aep6g <anonymous example.com> writes:
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.
May 29 2021
parent reply JN <666total wp.pl> writes:
On Saturday, 29 May 2021 at 22:26:48 UTC, ag0aep6g wrote:
 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.
I have to disagree. I don't see a good reason for this behavior and it's just one more thing to trip people. I think it'd be better if such thing was done explicit, something like: ```d Bar b = new Bar(); Foo* f2 = cast(Foo*)b.ptr; ```
Jun 10 2021
parent reply Paul Backus <snarwin gmail.com> writes:
On Thursday, 10 June 2021 at 21:25:35 UTC, JN wrote:
 I have to disagree. I don't see a good reason for this behavior 
 and it's just one more thing to trip people. I think it'd be 
 better if such thing was done explicit, something like:

 ```d
 Bar b = new Bar();
 Foo* f2 = cast(Foo*)b.ptr;
 ```
Isn't having to write out `cast(Foo*)` already pretty explicit?
Jun 10 2021
parent Imperatorn <johan_forsberg_86 hotmail.com> writes:
On Thursday, 10 June 2021 at 23:47:33 UTC, Paul Backus wrote:
 On Thursday, 10 June 2021 at 21:25:35 UTC, JN wrote:
 I have to disagree. I don't see a good reason for this 
 behavior and it's just one more thing to trip people. I think 
 it'd be better if such thing was done explicit, something like:

 ```d
 Bar b = new Bar();
 Foo* f2 = cast(Foo*)b.ptr;
 ```
Isn't having to write out `cast(Foo*)` already pretty explicit?
^
Jun 11 2021