how to implement a function in a different D source file

Paul Backus snarwin at gmail.com
Thu Nov 28 00:23:57 UTC 2019


On Wednesday, 27 November 2019 at 23:32:34 UTC, Omar wrote:
> this forks into a second question but I think still fits this 
> thread as it could just be seen as another form of the same 
> question.
> Is there a way to define some functions in the body of a class 
> definition, and define others outside of it in other places in 
> the
> source file ?

No, there isn't. You have to define all of a class's methods in 
the class body.

However, you can define free functions that can be called with 
the same syntax as methods using UFCS [1]. For example:

import std.stdio;

class C {
     void foo() { writeln("foo"); }
}

void bar(C c) { writeln("bar"); }

void main() {
     C c;
     c.foo();
     c.bar();
}

The main limitation is that, because `bar` is really a free 
function and not a method, it will not be inherited by C's child 
classes, and therefore cannot be overridden.

[1] https://dlang.org/spec/function.html#pseudo-member


More information about the Digitalmars-d-learn mailing list