Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Classes and Templates

Inheritance and Interfaces in D

Learn single inheritance in D: base classes, override, super, abstract classes, interfaces, virtual dispatch and casting with cast and typeid, with C vtable stand-ins.

D classes support single inheritance: a class extends at most one base class, but may implement any number of interfaces. Methods are virtual by default, so calling a method through a base-class reference runs the version of the actual object. This lesson shows how that works and how C code can model it with a table of function pointers.

Extending a class

D
class Shape
{
    string name() const { return "shape"; }
    double area() const { return 0; }
}

class Circle : Shape
{
    private double r;
    this(double r) { this.r = r; }

    override string name() const { return "circle"; }
    override double area() const { return 3.14159265 * r * r; }
}

The keyword override is required when you replace a base method. If you misspell the name or change the signature, the compiler tells you instead of silently adding a new method. Inside a subclass, super.name() calls the base version, and super(args) inside a constructor runs the base constructor; if you do not write it, the compiler calls super() for you when the base has a no-argument constructor.

D
Shape s = new Circle(2.0);
writeln(s.name());   // circle  (dynamic dispatch)

The static type of s is Shape, the dynamic type is Circle, and the call is resolved at run time.

How virtual dispatch works

Each class with virtual methods has a vtable: an array of function pointers. Each object stores a hidden pointer to the vtable of its class. A virtual call loads the pointer from the object, indexes the table and jumps. You can model this directly.

C Stand-in: a hand-made vtable

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 loop is written once against Shape, yet each element runs its own code. That is polymorphism.

Abstract classes

A class with at least one abstract method cannot be instantiated. It exists to define a contract plus shared code:

D
abstract class Animal
{
    abstract string sound() const;

    void speak() const
    {
        writeln("The animal says ", sound());
    }
}

class Dog : Animal
{
    override string sound() const { return "woof"; }
}

new Animal() is a compile error; new Dog() works because Dog implements every abstract method.

Interfaces

An interface lists methods without data. A class can implement several:

D
interface Drawable { void draw() const; }
interface Resizable { void resize(double factor); }

class Sprite : Drawable, Resizable
{
    double scale = 1;
    void draw() const { writeln("sprite x", scale); }
    void resize(double f) { scale *= f; }
}

Interface methods can also have final bodies or static members, which gives you reusable default behavior without multiple inheritance of state. When a class both extends a base class and implements interfaces, the base class is written first: class C : Base, I1, I2.

An interface reference is different internally: an object has a separate interface pointer for each interface it implements, so converting between them adjusts the pointer. Stand-in code can model an interface as a "fat pointer": data pointer plus table.

C Stand-in: an interface as a fat pointer

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.

Two unrelated types satisfy one interface, and the calling loop does not know which is which.

Casting and type tests

Downcasting uses cast. It returns null if the object is not of that type, so it is safe:

D
Shape s = getShape();
if (auto c = cast(Circle) s)
{
    writeln("radius known: ", c.r);
}

Use typeid(s) to get the dynamic type's information, and s.classinfo.name for its name. Avoid long chains of casts: if you need them, a virtual method is usually the better design.

Common mistakes

  • Forgetting override: the compiler rejects it, so just add it.
  • Calling an overridable method from a constructor: in D it dispatches to the most derived version, which may not be constructed yet.
  • Slicing: D classes cannot be sliced, but structs can lose information when copied to a smaller type. Another reason to keep polymorphism in classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many base classes may a D class extend?

    D has single class inheritance, plus any number of interfaces.
  2. 2. What happens if you replace a base method and omit override?

    D requires override so typos and signature changes are caught by the compiler.
  3. 3. What does cast(Circle) s produce when s is not a Circle?

    A class downcast with cast yields null when the dynamic type does not match.
  4. 4. What does an abstract class prevent?

    Abstract classes can have data and code, but only concrete subclasses can be instantiated.

Summary

  • Single inheritance plus interfaces; override is mandatory.
  • Virtual calls go through a per-class vtable.
  • Abstract classes define contracts with shared code; interfaces define pure contracts.
  • cast is safe for classes and returns null on mismatch.

Next: Templates and Generics