struct vs class
Jonathan M Davis
jmdavisProg at gmx.com
Sun Nov 14 03:32:18 PST 2010
On Sunday 14 November 2010 03:08:49 spir wrote:
> Hello,
>
>
> There seems to be 2 main differences between structs & classes:
> 1. structs instances are direct values, implement value semantics; while
> class instances are referenced (actually "pointed") 2. classes can be
> subtyped/subclassed in a simple way; structs cannot be really subtyped --
> but there is the "alias this" hack
The main thing to remember between structs and classes is that classes are
polymorphic. If you want polymorphism, use a class. If you don't use a struct.
Now, if you want a type which is _always_ a reference, then you should probably
choose a class, but it's quite easy to have a struct which is a reference type
by having its member variables are on the heap and don't get deep copied be a
postblit constructor. It is more immediately clear, though, that a class is a
reference type.
You can get more nuanced on the reasons why you should pick a struct or a class,
but polymorphism is really what it generally comes down to. If you never intend
to subclass it or have it implement interfaces, then it should probably be a
struct.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list