Initializing const member post-construction?

Jerry Quinn jlquinn at
Mon Oct 27 21:12:25 PDT 2008

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?  What's the reason for not allowing this?


More information about the Digitalmars-d-learn mailing list