Martin Perry Martin Perry - 4 months ago 29
C++ Question

C++ const reference to class member variable assigned in ctor

In C++, is this going to work as expected, or will be there undefined behaviour in some cases

class Foo
const int & ref;
Foo() : ref(val) { val = 7; }
void SetVal(int v) { val = v; }

int val;

And I expect that
will "contain" value of

Why I am doing this... baceuse I want the variable to be read only from outside, but "assignable" from inside the class.


Yes, this will work as expected. val will have a valid location the moment you set ref to it. From then on, ref will just hold whatever is in val.