What is difference between struct and class?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Jun 3 06:01:15 UTC 2019


On Sunday, June 2, 2019 9:40:43 PM MDT Rnd via Digitalmars-d-learn wrote:
> On Monday, 3 June 2019 at 00:47:27 UTC, Adam D. Ruppe wrote:
> > On Monday, 3 June 2019 at 00:17:08 UTC, Rnd wrote:
> >> What additional features do classes offer in D?
> >
> > Classes support built-in runtime polymorphism through
> > inheritance. structs don't.
> >
> > As a result of this, classes are a little bit heavier
> > resource-wise and are semantically always object references.
>
> I am not clear if structs can have constructors (this) and
> whether they can be multiple? Also can data be made private and
> getters and setters used to access them?

Yes structs can have constructors (but no default constructor - the default
value of a struct is its init value, which is defined by the values that the
struct's members are directly initialized with), and structs can have all of
the various functions that a class can have. The can also use private,
public, and package just like classes can (but not protected, since structs
have no inheritance).

Basically, structs go wherever they're declared and don't have inheritance,
whereas classes are always reference types and have inheritance. In general,
besides that, their abilities are pretty much the same, though there are
some differences that stem from the fact that classes are always reference
types, whereas structs aren't. I'd advise reading

http://ddili.org/ders/d.en/index.html

If you want to know more about structs and classes specifically, then you
can go straight to the sections on them, but you're going to understand a
lot of things better if you just read through the book.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list