D provides support for classes and interfaces like in Java or C++.
Any class
type inherits from Object
implicitly.
class Foo { } // inherits from Object
class Bar: Foo { } // Bar is a Foo too
Classes in D are generally instantiated on the heap using new
:
auto bar = new Bar;
Class objects are always references types and unlike struct
aren't
copied by value.
Bar bar = foo; // bar points to foo
The garbage collector will make sure the memory is freed when no references to an object exist anymore.
If a member function of a base class is overridden, the keyword
override
must be used to indicate that. This prevents unintentional
overriding of functions.
class Bar: Foo {
override functionFromFoo() {}
}
In D, classes can only inherit from one class.
A function can be marked final
in a base class to disallow overriding
it. A function can be declared as abstract
to force base classes to override
it. A whole class can be declared as abstract
to make sure
that it isn't instantiated. To access the base class,
use the special keyword super
.