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++?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With