Martin Perry Martin Perry - 9 days ago 4
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
{
public:
const int & ref;
Foo() : ref(val) { val = 7; }
void SetVal(int v) { val = v; }

private:
int val;
}


And I expect that
ref
will "contain" value of
val
.

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

Answer

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.

Comments