I am getting unexpected value in second getter call which looks wrong to me, any specific reason for this happening?
#include<iostream>
using namespace std;
class Test {
public:
int &t;
Test (int x):t(x) { }
int getT() { return t; }
};
int main() {
int x = 20;
Test t1(x);
cout << t1.getT() << " ";
cout << t1.getT() << endl;
return 0;
}
CodePudding user response:
The problem here is that your code results in undefined behavior.
The constructor of Test
does not take a reference to an int but a copy, and due to int x
only being a temporary copy which is not guaranteed to live until your second function call you will end up with undefined behavior.
You would have to change your constructor to the following to make the code work properly:
Test(int& x) : t(x) {}
Now the reference you're working with in Test
will be the same x
as defined in main