Function implemented outside the class

John Colvin john.loughran.colvin at gmail.com
Sun Mar 23 15:20:37 PDT 2014


On Sunday, 23 March 2014 at 21:48:33 UTC, MarisaLovesUsAll wrote:
> Hi! I didn't find how to implement functions outside the class, 
> like in C++.
>
> C++:
> class MyClass
> {
>    void myFunc();
> };
> void MyClass::myFunc() { ... }
>
> Is it possible to do this in D ?
>
>
> Sorry for my bad English.
> Regards,
> Alexey

No, it's not possible.

However, Combining these 3 features:


UFCS (universal function call syntax, foo(x) can be rewritten as 
x.foo() )

private means private to the module, not private to the class

//one.d
module one;

class A
{
     private int i;
}

int getI(A c)
{
     return c.i;
}

//two.d
module two;

void main()
{
     auto a = new A;
     auto i = A.getI();
     assert(i == int.init);
}


Note that:

getI is just a normal function. It can still be called like 
getI(a);. This means they by definition aren't virtual and cannot 
override inherited methods.

the same syntax works for anything, not just classes. E.g. 
core.time.msecs can be called like this:
auto t = 42.msecs();
instead of this:
auto t = msecs(42);


More information about the Digitalmars-d-learn mailing list