Struct inheritance
Derek Fawcus
dfawcus+dlang at employees.org
Wed Dec 4 17:22:50 UTC 2024
On Wednesday, 4 December 2024 at 12:43:49 UTC, Richard (Rikki)
Andrew Cattermole wrote:
> Casting a pointer to the parent, would be ``@system``, so what
> it does is very much "good luck with that".
Which I guess is reasonable, or even have it as undefined
behaviour.
> In a situation such as:
>
> ```d
> struct Parent {
> void method1() {
> method2();
> }
>
> void method2() {
> }
> }
>
> struct Child : Parent {
> override void method2() {
> }
> }
> ```
>
> My general view is that you have to be a little bit smart about
> it.
>
> There may be reasons you would want something like this, but
> there is also reasons it might not be desired.
My thinking, and reason for asking, is that two different authors
may be involved. One would not wish the fact that someone had
Child inherit from Parent cause the behaviour of Parent to
change, that way lies madness.
Given these are structs, not classes; and the author of Parent
would have no expectation of anything other than its own method
being called.
> I want a way to reinterpret parent methods as if it was in the
> child if not overriden. At which point ``method1`` would see
> the child ``method2`` rather than the one in the parent.
Isn't that simply what I described as 'madness' above?
One would seem to be exposing the Parent method to an unexpected
code change, as one can not know what other Parent private state
may be updated based upon the call to method2 being changed.
That strikes me as causing non-determinism.
I could see a use for this sort of thing:
```d
struct Parent {
void method1() {
method3();
}
void method2() {
}
void method3() {
}
}
struct Child : Parent {
override void method2() {
method1();
}
override void method3() {
}
}
```
Where the Child call from method2() to method1() invokes the
Parent version, yet the Parent call from method1() to method3()
will only ever invoke the Parent version.
That means the behaviour of Parent stays consistent. To allow
method3() to be redirected, is classful behaviour, and should not
be forced upon an existing library of structs just because of
what the child did.
If one wants classes, use classes - as that sort of result is
expected to be possible there.
More information about the dip.ideas
mailing list