Initializing const member post-construction?

Steven Schveighoffer schveiguy at
Tue Oct 28 06:18:24 PDT 2008

"Jerry Quinn" wrote
> Hi.  I'm trying to port a C++ program to D as an exercise in exploring D. 
> As I'm doing this, I've run into a bit of confusion with the const system.
> I have something like
> class A {}
> class B {
>  const A a;
>  void init(A aa) { a = aa; }
> }
> This doesn't work, because dmd (2.020) complains that you can't initialize 
> a const member after the constructor.  The catch is that the value of aa 
> is not available at construction time, but only later on.  However, I'd 
> still like to declare that once set, the object referred to by a is const.
> The C++ code used a pointer, but it seemed to me like D's references were 
> more capable than C++'s, so I'm trying to use them.
> To me it seems like this should still be allowed.  Even though the object 
> referred to by a is const, the reference itself shouldn't need to be. 
> This seems morally equivalent to:
> const(A)* a;
> which is allowed by dmd.  In both cases I'm trying to tell the compiler 
> that the object referred to by a is const.
> Is there a way to do what I'm trying to do?

You can hide a behind a property:

class B {
  private A aPriv;
  void init(A aa)
     aPriv = aa;

  const(A) a() const { return aPriv;}

Now, do not use aPriv anywhere else in your code, and you should be all set. 
Use -inline when compiling and you should see no performance penalty.

> What's the reason for not allowing this?

I was unaware you could even set a in the constructor.  I don't think 
there's any general 'set once' type modifier.


More information about the Digitalmars-d-learn mailing list