From 63444ed552ea6b973ac44d688f36b9eca6b6e28e Mon Sep 17 00:00:00 2001 From: Johannes Loher Date: Fri, 13 Apr 2018 18:24:22 +0200 Subject: [PATCH] add section about classes --- hands-on_dlang.md | 63 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 2 deletions(-) diff --git a/hands-on_dlang.md b/hands-on_dlang.md index 9bd36f3..c06632c 100644 --- a/hands-on_dlang.md +++ b/hands-on_dlang.md @@ -217,8 +217,8 @@ type qualifiers: #### `immutable` -An object declared as `immutable` is enforced by the compiler to never change its -value. +An object declared as `immutable` is enforced by the compiler to never change +its value. ```D immutable int a; @@ -735,3 +735,62 @@ if ("key1" in map) { // checking if a key is in an associative array assert(map.length == 1); // associative arrays provide a .length property map.remove("key1"); // remove a key from an associative array ``` + +### Classes + +D's `class`es are very similar to Java's `class`es. + +Any `class` type implicitely inherits from `Object`. + +```D +class Foo { } // implicitely inherits from Object +class Bar : Foo { } // Bar inherits from Foo +``` + +`class`es are usually instantiated on the GC heap using `new`: + +```D +auto bar = new Bar; +``` + +In contrast to `struct`s, `class`es are reference types: + +```D +Bar bar = foo; // bar points to foo +``` + +#### Inheritance + +If a member function of a base class if overwritten, the `override` keyword must +be used: + +```D +class Bar: Foo { + override void functionFromFoo() {} +} +``` + +Classes can only inherit from a single class + +#### Final and abstract member functions + +* A function can be marked `final` in a base class to disallow overriding it. +* A function can be declared as `abstract` to force derived classes to override + it. +* A whole class can be declared as `abstract` to make sure that it isn't + instantiated. +* `super(…)` can be used to explicitly call the base constructor. + +#### Checking for identity + +The `==` operator compares the content of two class objects. Checking for +identity is done using the `is` operator. Coparing to `null` is only possible +with this operator: + +```D +MyClass c; +if (c == null) // error + /* … */ +if (c is null) // ok + /* … */ +```