Why are structs and classes so different?

Walter Bright newshound2 at digitalmars.com
Mon May 16 03:51:57 UTC 2022


On 5/15/2022 8:26 AM, Kevin Bailey wrote:
> I'm trying to understand why it is this way.
Great question.

The difference, in a nutshell, is a struct is a value type, and a class is a 
reference type. This difference permeates every facet their behavior.

In C++, a struct can designed to be a value type or a reference type. But C++ 
does not recognize the difference, and so you can pass a reference type by 
value, which leads to all sorts of problems. You'll see C++ structs confused 
about what they are, as the designer didn't know the difference and would put a 
foot in both camps. A common example of this confusion is putting in virtual 
functions but neglecting to make the destructor virtual.

D draws a hard distinction between the two, making it both self-documenting, and 
heading off all sorts of errors from misusing one as the other.

A reference type is inherently a polymorphic type (i.e. virtual functions). 
Polymorphism via inheritance makes no sense for a value type.

Copy constructors make no sense for a polymorphic type, but are sensible for a 
value type.

And so on.

A strong distinction between value and reference types has turned out well for 
D. Naturally, some people still want a type to be both a floor wax and a dessert 
topping, but D is purposely going to make it difficult to do that.

P.S. Yes, you can pass a struct by reference with the `ref` keyword. That's not 
polymorphic behavior, though.

P.P.S. Yes, you can allocate a class instance on the stack rather than the GC by 
using the `scope` storage class. It will still be a reference type, but the 
compiler won't allow that reference to live longer than its stack frame. Java 
will automagically allocate classes on the stack if it can determine it cannot 
escape.


More information about the Digitalmars-d-learn mailing list