Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# readonly in C++ (subtle differences to const)

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++?

like image 593
mafu Avatar asked Jan 15 '23 01:01

mafu


1 Answers

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).

like image 128
Luchian Grigore Avatar answered Jan 24 '23 16:01

Luchian Grigore