Skip to content
Structs vs Classes
step 1/5

Reading — step 1 of 5

Learn

~1 min readStructs vs Classes and Errors

D has both struct (value type) and class (reference type) — like C# but with sharper distinctions.

Structs — value semantics, stack-allocated:

struct Point {
    int x, y;
    int distSquared() { return x*x + y*y; }
}

auto p = Point(3, 4);    // direct construction
auto p2 = p;              // copy
p2.x = 10;
writeln(p.x);             // still 3
  • No inheritance (only composition)
  • No virtual methods
  • Initialized to init value (zeros) by default
  • Used for small, lightweight data

Classes — reference semantics, heap-allocated:

class Animal {
    string name;
    this(string n) { name = n; }
    string sound() { return "..."; }
}

class Dog : Animal {
    this(string n) { super(n); }
    override string sound() { return "woof"; }
}

auto d = new Dog("Rex");
Animal a = d;            // upcast
writeln(a.sound());       // "woof" (virtual dispatch)
  • Single inheritance + multiple interface implementation
  • override keyword required (catches typos)
  • Methods virtual by default; final to lock down
  • Always heap-allocated, accessed via reference

When to use which:

  • struct — small, immutable-ish, value semantics (Point, Pair, RGBA)
  • class — needs polymorphism, identity matters, lots of state

Auto-generated == and hashCode for structs. For classes, == is reference equality unless you override opEquals.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…