Why are structs and classes so different?

H. S. Teoh hsteoh at quickfur.ath.cx
Mon May 16 17:32:39 UTC 2022


On Mon, May 16, 2022 at 05:02:57PM +0000, IGotD- via Digitalmars-d-learn wrote:
> On Sunday, 15 May 2022 at 16:08:01 UTC, Mike Parker wrote:
> > 
> > `scope` in a class variable declaration will cause it to the class
> > to be allocated on the stack.
> > 
> 
> Common practice is that a class has class members itself. So where are
> they allocated? Most likely is only the top class that is on the
> stack, the class members are allocated on the heap because the
> constructor is already compiled.
> 
> That scope isn't that useful unless you have it like C++, that expands
> class members in the parent class.
[...]

C++ embedded class members suffer from the same problems as by-value
class objects. I.e., object truncation when you assign a derived class
member to it.  The only way to avoid this problem in C++ is to turn them
into pointers, at which point it becomes equivalent to D class members
that by default are reference types.

In D, if you have members that you want to have by-value semantics, just
use structs instead.  In general, in my own D code I rarely use classes.
Structs are my go-to constructs; only when there is good reason I use
classes -- usually when I need inheritance, which is also when by-value
types would encounter truncation issues.  Since it *is* possible to pass
around pointers to structs, I don't really see much reason for using
classes if you don't need inheritance, i.e., when you'll never run into
truncation issues.

So IMO D's design of structs and classes makes much more sense than in
C++, where `struct` and `class` means essentially the same thing (just
with some different default protections -- just lip gloss, really), and
where the unclear intention of whether you want a by-value or
by-reference type means that truncation issues keep cropping up. D's
choice to settle this decision and bake it into the language IMO was the
right choice. (Now obviously, this implies that the usage of structs /
classes will differ between D and C++... but then again, that's why this
is D, not C++. I want to speak idiomatic D, not D with a C++ lisp. :-P)


T

-- 
The richest man is not he who has the most, but he who needs the least.


More information about the Digitalmars-d-learn mailing list