Why are structs and classes so different?

Kevin Bailey keraba at yahoo.com
Sun May 15 15:26:40 UTC 2022


I've done some scripting in D over the years but I never dug into 
D until recently. I'm going through Learning D and I was reminded 
that structs and classes are so different.

- struct methods are non-virtual while class methods are virtual
- Thus, structs can't inherit, because how would you find the 
child's destructor given a parent pointer?
- On the stack, structs by-value but classes are by-reference

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.

One problem that this causes is that I have to remember different 
rules when using them. This creates the additional load of 
learning and remembering which types are which from someone 
else's library.

A bigger problem is that, if I have a struct that I suddenly want 
to inherit from, I have to change all my code. In addition to 
that work, in both of these cases, one could easily do it wrong:

// Fine with a struct, fatal with a class.
Foo foo;

At least in C++, the compiler would complain. In D, not even a 
warning.

Why is it this way? What is the harm of putting a class object on 
the stack?



More information about the Digitalmars-d-learn mailing list