what is wrong with this code, why do I get wrong answer:
class X
{
private:
const int a;
const int& b;
public:
X(): a(10) , b(20)
b refers to a temporary. What you have read (when printing) is an invalid location by the time it is read since the temporary 20 has technically gone out of scope.
To explain inconsistent results:
It is undefined behavior. What you see may be different if you:
xYou should always always avoid undefined behavior.
But why would the value change? Your reference likely refers to a stack address which has been rewritten (e.g. reused) by the time it's printed.