On Saturday, 9 March 2024 at 22:03:34 UTC, Liam McGillivray wrote:
Secondly, I found out that interfaces can't have variables.
What!? That's crazy! Why wouldn't they? They totally should.
Doesn't this mean that I will need to use getter and setter
functions instead of direct access when using interfaces? I
don't like this.
An interface just defines an interface, a set of method
signatures that a class can respond to, and must implement. If
you want storage and functionality, you can define a base class.
A derived class can inherit from either one base class or one or
more interfaces. Or a combination, but multiple inheritance is
not a well-liked idea.
```d
class Map {
int someVar = 3;
void someFunc() {
// default behavior
writeln("hello");
}
}
class CustomMap!TierType : Map {
override void someFunc() {
// new behavior
writefln("good day %s %s", someVar, TierType.stringof);
}
}
void main() {
auto map = new Map;
map.someFunc() // hello
map = new CustomMap!uint;
map.someFunc() // good day 3 uint
}
```
In the last line of this code, the variable `map` is still of
type `Map` (chosen by `auto` when it received `new Map`, but the
actual class object it references is of type `CustomMap!uint`,
hence calling a virtual function like `someFunc` calls the
derived version instead of the original. Note that functions
that take template arguments (not included here) don't
necessarily follow this behavior; mixing templated methods and
inheritance has some pitfalls.