Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Classes and Templates

Classes and Objects in D

Learn how D classes work: heap-allocated reference types, constructors, destructors, this, properties, const and final members, and how classes differ from structs.

D has two ways to define your own types: structs, which are values copied on assignment, and classes, which are references to objects that live on the garbage-collected heap. Classes are the tool for object-oriented design: inheritance, virtual methods and interfaces. This lesson covers the basics of declaring and using them.

The D compiler cannot run on this site. D code in this chapter is read-only; the runnable examples are C stand-ins on the C runner that model the same ideas (reference semantics, constructors, destructors, virtual tables). Output is shown only where it follows directly from the code.

Declaring a class

D
class Account
{
    private string owner;
    private double balance;

    this(string owner, double opening = 0.0)
    {
        this.owner = owner;
        this.balance = opening;
    }

    void deposit(double amount)
    {
        balance += amount;
    }

    double getBalance() const
    {
        return balance;
    }
}

Constructors are named this. Parameters may have default values, as in any D function. Inside a method, this is the current object; you only need to write it when a parameter shadows a member, as above.

Create an object with new:

D
auto a = new Account("Mina", 100.0);
a.deposit(25.5);

There is no delete in everyday code: the garbage collector reclaims the object when nothing refers to it any more (see the garbage collector lesson).

Reference semantics

A class variable holds a reference. Assigning one variable to another copies the reference, not the object:

D
auto a = new Account("Mina", 100);
auto b = a;          // same object
b.deposit(50);
// a.getBalance() is now 150 too

A class variable can also be null. Calling a method through a null reference crashes at run time (a segmentation fault or a null-dereference error depending on the build), so check with if (a is null). Use is and !is to compare references (identity), and == to compare contents, which calls opEquals.

C Stand-in: reference versus value semantics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first pair shares one object, so both print 150. The struct pair are independent copies: 100 and 150.

Constructors and destructors

A class can have several constructors with different parameter lists. A constructor can call another with this(...):

D
class Point
{
    int x, y;
    this() { this(0, 0); }
    this(int x, int y) { this.x = x; this.y = y; }
}

A destructor is written ~this(). For classes it runs when the garbage collector finalizes the object, at a time you cannot predict, and possibly never before the program ends. Never rely on it to release scarce resources such as files or locks; use scope(exit) or a struct with a destructor for that (see scope and RAII).

C Stand-in: constructor and destructor order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Members: access, const and final

Members are public by default in D. Use private (visible inside the module, not just the class), protected (visible in subclasses) or package to narrow them. Note that private is per module: other classes in the same file can touch your private members.

D
class Temperature
{
    private double kelvin;

    @property double celsius() const { return kelvin - 273.15; }
    @property void celsius(double c) { kelvin = c + 273.15; }
}

@property lets you call these without parentheses: t.celsius = 20;. A const method promises not to modify the object. Methods in a class are virtual by default; mark one final to forbid overriding and to allow the compiler to call it directly, which is faster. You can also write final class C to forbid subclassing altogether.

Classes versus structs

struct class
Semantics value (copied) reference
Storage stack or inline GC heap (usually)
Inheritance no yes (single)
Virtual methods no yes, by default
Destructor timing deterministic when collected

Choose a struct for small data like points, colors or vectors, and a class when you need polymorphism or shared identity.

flowchart LR
    V["Class variable"] --> O["Object on the GC heap"]
    W["Another variable"] --> O
    S["Struct variable"] --> D["Its own copy of the data"]

Two class variables can name one object; a struct variable always owns its data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does auto b = a; do when a is a class reference?

    Class variables are references. Assignment copies the reference, so changes through b are visible through a.
  2. 2. How do you compare two class references for identity?

    is tests identity. == calls opEquals and compares contents.
  3. 3. When does a class destructor ~this() run?

    Class destructors are tied to garbage collection, so do not use them to release scarce resources promptly.
  4. 4. What does final on a method do?

    Methods are virtual by default; final makes them non-virtual so subclasses cannot override them.

Summary

  • Classes are reference types created with new and collected by the GC.
  • Constructors are named this; destructors ~this() run at collection time.
  • Assignment copies the reference; use is for identity, == for equality.
  • Members are virtual by default; final and const tighten the contract.
  • Prefer structs for small value data, classes for polymorphism.

Next: Inheritance and Interfaces