4

There are many questions about the C++ equivalent of readonly in C# mentioning const. However, so far I found none that, as far as I can tell, is actually correct or even mentions the detail I am after here.

Readonly fields can be set (even multiple times) within the ctor (spec). This allows performing various operations before finally deciding on the value. Const in C++, on the other hand, behaves subtly differently (in both C++ and C#) in that it requires the final value to be available before the ctor runs.

Is there a way to still achieve the behavior of readonly in C++?

0

2 Answers 2

6

Yes, use const - the value doesn't have to be known at compile-time:

struct X
{
    const int a;
    X(int y) : a(y) {}
};

//...
int z;
cin >> z;
X x(z);   //z not known at compile time
          //x.a is z

The other alternative is to use a user-defined structure that allows setting only once, but this is overkill (and you probably couldn't enforce this at compile-time anyway).

1
  • Thank you, I stand corrected. (I think I messed up C# const with C++ const.)
    – mafu
    Commented Nov 13, 2012 at 14:22
3

Not really.

What you can do is protect a field, so that it must be accessed (from outside at least) by a getter, and you may create a setter for it that only allows itself to be called once.

Otherwise, const is your best bet.

Not the answer you're looking for? Browse other questions tagged or ask your own question.