Struct inheritance
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Mon Sep 23 14:57:38 UTC 2024
On 24/09/2024 2:52 AM, Ogion wrote:
> On Thursday, 19 September 2024 at 15:56:06 UTC, Richard (Rikki) Andrew
> Cattermole wrote:
>> …
>>
>
> Would be nice to have proper struct inheritance but there are a lot of
> things we have to consider.
>
> What about slicing?
>
> ```D
> struct A {
> int x;
> }
>
> struct B : A {
> int y;
> this(int x, int y) {
> super(x);
> this.y = y;
> }
> }
>
> void main() {
> B b1 = B(1, 2), b2 = B(3, 4);
> A* p = &b2;
> *p = b1;
> writeln(b2); // B(1, 4)
> }
> ```
>
> If we want something better than `alias this`, we have to prohibit
> implicit partial assignment via pointer/reference. When it’s necessary,
> it would still be possible with `*p = cast(A)b1;`.
It is probably better to completely disable casting up the hierarchy in
``@safe`` code. If you need that, use ``opCast``.
It is not like with classes, where its guaranteed to have an allocation
containing the entire thing, with a vtable.
Only concern is when you've got a pointer to a struct, and you cast up.
``opCast!(A*)`` support is likely what we want I think.
I'm not sure how we'd do that one. Maybe an attribute?
More information about the dip.ideas
mailing list