Struct inheritance
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Tue Dec 3 23:18:12 UTC 2024
On 04/12/2024 10:37 AM, Derek Fawcus wrote:
> On Tuesday, 3 December 2024 at 20:45:32 UTC, Richard (Rikki) Andrew
> Cattermole wrote:
>
>>> Would your proposal allow:
>>>
>>> ```d
>>> struct Grandad {
>>> }
>>>
>>> struct Dad : Grandad {
>>> }
>>>
>>> struct Child : Dad {
>>> }
>>> ```
>>>
>>> (I'm not sure if the scheme I mention does, I'd have to reread the
>>> specs; but I believe it doesn't).
>>
>> Yes.
>
> OK.
>
> I'd suggest that the member variable version of 'alias this' is also a
> form of embedding / composition.
>
> It allows one to control the exact in-memory layout of the struct so
> defined. Whereas AFAICT, the inheritance suggestion does not.
>
> Issues/Questions with inheritance suggestion:
>
> 1. What is the in memory layout?
> (Presumably the 'parent' elements simply appear first in memory).
Yes, that would be my thought.
> 2. Inability to control in memory layout.
If you need the control between last field of parent, and first of
child, I suspect that this isn't the language feature for you.
But if we do need to solve it, we could solve it later on with an
attribute. I don't think there is a better way to do it than an
attribute, so this can be done later on should we need it, rather than
arguing about it now.
> 3. What type is passed to a parent struct member function when called on
> the child.
> (Presumably it is the class behaviour of passing the child stuct,
> with 'isA' relations)
> (If not, then there are two different behaviours for inheritance -
> class vs struct)
A class will pass a this pointer typed as its class, not a child.
```d
import std.stdio;
void main() {
Child child = new Child;
child.method();
Parent parent = child;
parent.method;
}
class Parent {
void method() {
writeln(typeof(this).stringof);
}
}
class Child : Parent {
override void method() {
super.method();
writeln(typeof(this).stringof);
}
}
```
Will output:
```
Parent
Child
Parent
Child
```
Struct inheritance would have the same output.
> 4. What other parts of the class behaviour will apply?
> (i.e. will the class implicit mutex lock now be instantiated)
> (if not, then classes and structs using inheritance will have
> different threading behaviour)
There is no vtable, no root type (Object class provides the mutex).
Therefore unless its stated, no behavior from classes is coming across
to structs.
Note: classes do not lock the mutex automatically for you. You must
specify the synchronized keyword to make it do it. Unless specified by
the user, the temporal properties of each match.
Existing structs will not change behavior.
More information about the dip.ideas
mailing list