Function implemented outside the class

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 24 13:51:48 PDT 2014


On Mon, 24 Mar 2014 16:02:25 -0400, MarisaLovesUsAll <marusya at 2ch.hk>  
wrote:

> On Monday, 24 March 2014 at 01:34:22 UTC, Matej Nanut wrote:
>> Hello!
>>
>> You can implement static functions that act like members, like so:
>>
>> ---
>> void myFunc(MyClass c) { ... }
>> ---
>>
>> Which you will be able to call like:
>>
>> ---
>> auto c = new MyClass();
>> c.myFunc();
>> ---
>>
>> because of uniform function call syntax (UFCS).
>>
>> But they won't be real methods (virtual member functions), which means  
>> they
>> can't be overridden.
>>
>> Note that you can use the class's private members in such functions,
>> because private things in D are private to the file (module) instead of  
>> the
>> containing class or struct.
>>
>> I don't think it's possible to do the same thing as in C++ though; but I
>> might be wrong.
>
> 2 all:
> Thanks for replies!
>
>> Why would you like to do that?
>
> I planned to use it to take event handling out from class (and put it in  
> another file), but now I see that isn't a good idea.
> class App
> {
>      void updateEvents(SDL_Event event) { ... }
> }
>
>
> By the way, it would be useful if it was written somewhere that  
> implementation outside the class is impossible.

Implementation outside the class is not exactly possible, but it IS  
possible to separate declaration from implementation, see D interface  
(.di) files. You can't split an implementation into two files, however.

Note, there are serious drawbacks for using an interface file, most  
importantly eliminating the ability to inline. It should only be used,  
IMO, when you need to hide the implementation, as in a closed-source  
project.

-Steve


More information about the Digitalmars-d-learn mailing list