what was wrong with struct & class in C++?

Walter Bright newshound1 at digitalmars.com
Wed Dec 12 21:10:04 PST 2007


BC wrote:
> I thought it was a great idea to allow both value semantics
> and pointer semantics for the same types in C++ by the simple
> addition of a * or &. What was wrong with that that needed
> to be fixed in D? GC could have been done without changing
> this. Now in D template code doesn't know which
> semantics apply and structs can't inherit. If you write
> something as a struct and then realise you need inheritance
> you're stuck. D has so many good ideas it's a shame to see
> it broken in this way...

It's a good question. D structs are designed to represent value types, 
and classes as reference types. The two have very different uses and 
characteristics. C++ allows them to be mixed up together, with program 
bugs as the usual result.

For example, the slicing problem. If you inherit from a value type, and 
then add members, then everyone who uses the value type by value 
"slices" off the additional members.

Virtual functions make no sense for value types, and non-virtual 
functions are a recipe for disaster in reference types (hence the 
exhortation to not forget to make your destructors virtual if deriving 
from them, a lame bit of advice because base classes cannot control how 
they are used).

In C++, one designs a class to be a reference type or a value type. 
Interestingly, I've never once seen in documentation for a C++ class 
whether it is supposed to be used by reference or by value.

Clearly distinguishing value types from reference types:

1) Indicates to the user how a type is to be used
2) Allows for the correct semantic defaults
3) Eliminates whole categories of bugs that are impractical to detect in C++



More information about the Digitalmars-d mailing list