I a trying to store int by reference as data member of class. I expected that is object get int by refernce than if I increase the reference from outside its increase the value inside the object.
class A
{
private :
int& x;
public:
A(int y) : x(y)
{
cout << "A's ctor x = " << x << endl;
}
void print()
{
cout << "x = " << x << endl;
}
};
int main()
{
int i = 8;
A a(i);
a.print();
++i;
a.print();
}
The output is :
A's ctor x = 8
x = 8
x = 8
Why x isnt 9?
The issue is that you're binding a temporary (the constructor parameter y) to a reference. The lifetime of the temporary is restricted to the constructor, but your reference lives on, becoming a "dangling" reference. This is what a reasonable compiler has to say about the matter:
crap13.cpp:10:18: warning: binding reference member 'x' to stack allocated parameter 'y' [-Wdangling-field]
A(int y) : x(y)
You can "fix" this by making the constructor parameter a reference:
A(int& y) : x(y)
but you must ensure that whatever is passed as argument to the constructor outlives the object being constructed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With