Meaning of const

Jonathan M Davis jmdavisProg at
Tue Jan 24 16:06:47 PST 2012

On Tuesday, January 24, 2012 15:52:50 H. S. Teoh wrote:
> Hi all,
> I'm a bit confused by what 'const' means when used as part of a member
> function's signature:
> class A {
> int x;
> const int f1() { ... }
> int f2() const { ... }
> const(int) f3() { ... }
> }
> Is there a difference between f1 and f2? If not, which is the preferred
> syntax? If yes, what is the meaning of 'const' in either case?
> I tried various code inside f1 and f2, and it seems in both of them I
> can't change x, which appears to mean that 'const' in this case refers
> to immutability of the class object? Is this correct?
> What exactly does 'const' mean in f3? That the returned int cannot be
> modified?
> Confused by const syntax,

const on a return value means that the return value is const. const on a 
member function means that the invisible this argument is const (meaning that 
you can't call non-const member functions within that function or mutate any 
member variables). You can think of it like this

int f2() const


int f2(const A this)

Now, the confusing part is the fact that unlike C++, D allows you to put the 
const for making the function on the _left-hand_ side of the function (C++ 
only lets you put it on the right). This is to increase consistency between 
modifers (public, override, pure, etc.) - they _all_ can go on both the right 
and left (which is very unfortunate in the case of const and immutable IMHO). 
That means that const (and immutable) always modify the function rather than 
the return value unless you use parens.

So, while a C++ programmer expects that

int f2() const

means that f2 is const, they're likely to be surprised by the fact that in

const int f1()

it's the int that's const, not f1. It's only in the case of

const(int) f3()

that the return value is const. You could, however, have both

const(int) f4() const

in which case both the return value and the function are const.

Now, having a const return value is rather pointless in the case of int, since 
it's a value type and would juts be copied. It matters a great deal more with 
a pointer or referenc type. e.g.

const(int*) func()


ref const(int) func()

or in the case of your A class,

const(A) func()

In those cases, it protects the return value from being mutated, since there's 
actually something to protect from mutation given that the return value is not 
a value type.

Hopefully, that clears things up.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list