Why are structs and classes so different?
Guillaume Piolat
first.last at gmail.com
Sun May 15 16:00:53 UTC 2022
On Sunday, 15 May 2022 at 15:26:40 UTC, Kevin Bailey wrote:
> I'm trying to understand why it is this way. I assume that
> there's some benefit for designing it this way. I'm hoping that
> it's not simply accidental, historical or easier for the
> compiler writer.
Perhaps someone more informed will chime in, but there is a
reason to avoid object inheritance with value types, and force
them to be reference types.
https://stackoverflow.com/questions/274626/what-is-object-slicing
If we want to avoid that problem, then object with inheritance
and virtual functions have to be reference types.
But you still need values types. So now you have both struct and
class, like in C# (Hejlsberg, 2000).
For an escape hatch, D has library ways to have structs with
virtual functions (there is a DUB package for that), and classes
on the stack (Scoped!T, RefCounted!T, a __traits).
More information about the Digitalmars-d-learn
mailing list