Classes or stucts :: Newbie

Jonathan M Davis jmdavisProg at gmx.com
Mon Dec 20 01:29:13 PST 2010


On Monday 20 December 2010 01:19:31 spir wrote:
> On Sun, 19 Dec 2010 21:33:56 -0500
> 
> bearophile <bearophileHUGS at lycos.com> wrote:
> > >So, putting classes on the stack kind of negates the whole point of
> > >having both structs and classes in the first place.<
> > 
> > This is false, the definition of D class instance doesn't specify where
> > the instance memory is allocated.
> 
> For me, the important difference is that classes are referenced, while
> structs are plain values. This is a semantic distinction of highest
> importance. I would like structs to be subtype-able and to implement
> (runtime-type-based) polymorphism.

Except that contradicts the facts that they're value types. You can't have a 
type which has polymorphism and is a value type. By its very nature, 
polymorphism requires you to deal with a reference.

C++ allows you to put classes on the stack. It even allows you to assign a 
derived type to a base type where the variable being assigned to is on the 
stack. The result is shearing. The only part assigned is the base type portion, 
and the data which is part of the derived type is lost. That's because the 
variable _is_ the base type. A value type _is_ a particular type _exactly_ and 
_cannot_ be any other type. This is distinctly different from a reference of a 
base type which points to an object which is of a derived type. In that case, 
the variable is a reference of the base type, but the object referenced is in 
fact the derived type. The indirection allows you to use the derived type as if 
it were the base type. It allows you to use polymorphism. Without that 
indirection, you can't do that.

So, you _could_ make structs have inheritance, but doing so would introduce 
shearing, which causes a number of problems. One of the main reasons that 
structs in D do _not_ have inheritance is to avoid shearing.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list