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 reference 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.
final
in a base class to disallow overriding
it
abstract
to force base classes to override
it
abstract
to make sure
that it isn't instantiated
super(..)
can be used to explicitly call the base constructor
For class objects, the ==
and !=
operators compare the contents of the objects.
Therefore, comparing against null
is invalid, as null
has no contents.
The is
compares for identity. To compare for nonidentity, use e1 !is e2
.
MyClass c;
if (c == null) // error
...
if (c is null) // ok
...
For struct
objects all bits are compared,
for other operand types, identity is the same as equality.