Martin Perry Martin Perry - 1 year ago 120
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download