D Easy · Lesson 1 · On the house

Classes and inheritance

Reference-type classes, constructors, single inheritance, virtual methods by default, override, and super. Lesson 1 is free — on the house.

Lessons · D Easy · Lesson 1 of 10 · On the house

Classes and inheritance

Reference-type classes, constructors, single inheritance, virtual methods by default, override, and super.

Illustration for D
Lesson 1 is on the house.

class Animal { ... } declares a reference type. Instances are created with new Animal(...) on the GC heap; a class variable is a reference and starts as null.

Assigning a class reference copies the reference, not the object: both names refer to one instance. Use a struct when you want value semantics.

D has single inheritance: class Dog : Animal. Every class implicitly derives from Object, which supplies toString, opEquals, and toHash.

Non-final, non-private, non-static member functions are virtual by default. Overriding requires the override keyword, so a typo in the name is a compile error.

super(...) calls the base constructor; super.method() calls the base version of a method. final stops further overriding.

cast(Dog) animal is a checked downcast: it returns null if the object is not a Dog.

classes

import std.stdio;

class Animal
{
    string name;
    this(string name) { this.name = name; }
    string sound() { return "..."; }
    override string toString() { return name ~ " says " ~ sound(); }
}

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

class Puppy : Dog
{
    this() { super("pup"); }
    override string sound() { return super.sound() ~ "!"; }
}

void main()
{
    Animal[] zoo = [new Animal("rock"), new Dog("rex"), new Puppy()];
    foreach (a; zoo) writeln(a);
    Animal ref2 = zoo[1];
    ref2.name = "max";
    writeln(zoo[1].name);
    writeln(cast(Dog) zoo[0] is null, " ", cast(Dog) zoo[2] !is null);
    Animal nothing;
    writeln(nothing is null);
}
Match this when you type.

Quiz

Are D class member functions virtual by default?

Quiz

What does cast(Dog) a return when a is not a Dog?

Quiz

What keyword is required when a method replaces a base method?

Quiz

What does Puppy's sound() return?

Check

Match the still for: Classes and inheritance.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.