I was told the reference variable must be initialized in the initialization list, but why this is wrong?
class Foo
{
public:
Foo():x(0) {
y = 1;
}
private:
int& x;
int y;
};
Because 0 is a temporary object? If so, what kind of object can reference be bound? The object which can take an address?
Thanks!
0 is not an lvalue, it’s an rvalue. You cannot modify it, but you’re trying to bind to a reference where it could be modified.
If you make your reference
const, it will work as expected. Consider this:This obviously is a no-go. But
const&‘s can be bound to temporaries (rvalues):Note that the life-time of the temporary is ended at the completion of the constructor. If you make static-storage for your constant, you’ll be safe: