const method and return type

Jakob Ovrum jakobovrum at gmail.com
Fri Dec 13 16:38:02 PST 2013


On Friday, 13 December 2013 at 23:46:14 UTC, Andrea Fontana wrote:
> class A
> {
>     auto getter() const
>     {
>         return property;
>     }
>
>     int property = 0;
> }
>
>
> Please notice that getter method is marked as const. Why this 
> method return "const int"?

`const` as a function attribute just marks the implicit 
this-reference parameter as const - apart from the necessary 
syntax deviation, it works like any other parameter. Thus, inside 
`getter`, `typeof(this)` is `const(A)`, and since const is 
transitive, that means `typeof(this.property)` is `const(int)`.

If you explicitly specify the return type as `int`, then 
`property` is implicitly converted from `const(int)` to `int`, 
which is legal since `int` has no mutable indirection.


More information about the Digitalmars-d-learn mailing list