Method definition

Paul Backus snarwin at gmail.com
Wed Jul 21 12:39:13 UTC 2021


On Wednesday, 21 July 2021 at 12:08:21 UTC, Tim Gunesh wrote:
> Is it possible to define methods outside the class in C ++ 
> style? Something like this:
>
> ```d
> class Parent{
>    void Print();
> }
>
> void Parent.Print(){
>    writeln("Hello, D!");
> }
> ```

No, it's not possible.

However, [uniform function call syntax][1] allows functions 
defined outside of a class to be called as though they were 
methods. For example:

```d
class Parent {}

void Print(Parent p)
{
     writeln("Hello, D!");
}

void example()
{
     Parent p = new Parent;
     p.Print(); // passes `p` as first argument
}
```

[1]: 
https://tour.dlang.org/tour/en/gems/uniform-function-call-syntax-ufcs


More information about the Digitalmars-d-learn mailing list