Embarrassed to ask this question because it seems so trivial but genuinely curious...

Steven Schveighoffer schveiguy at gmail.com
Thu Jan 27 18:05:14 UTC 2022


On 1/27/22 12:42 PM, WhatMeWorry wrote:

> Assuming I can speak in correct programmer-ese: I was wondering why the 
> qualifiers were placed after the function parameter list (int i).  Just 
> for fun, I moved to type qualifiers before the function definitions 
> "this" (like a return type?) and the output was  exactly identical.  So 
> I guess my question is, is this just a matter of esthetics or is some 
> more nuanced goal at work here?

For constructors, being on the front is not misleading. But for a member 
function that returns a value, take a look:

```d
struct S
{
    int * x;
    const int *foo() { return x; }
}
```

What do you think happens here?

The answer, is that this is a compiler error. The error is that the 
`const` applies to the `this` parameter and *not* the return value. So 
you are accepting a `const S`, and trying to return its member `x` as a 
plain `int *`.

This is why we always recommend putting the `this` modifiers at the end 
of the function to make it visually clear that they don't apply to the 
return value.

-Steve


More information about the Digitalmars-d-learn mailing list