#include <iostream>
using namespace std;
class A {
public:
int i;
A(int j) : i(j){ cout << "A::A()" << '\n';}
~A(){ cout << "A::~A()" << '\n';}
};
A& fun2() {
A a1(10);
A &aref = a1;
return aref;
}
int main() {
A &a2 = fun2();
cout << "a2.i : " << a2.i << '\n';
a2.i = 20;
cout << "a2.i : " << a2.i << '\n';
fun2().i = 30;
cout << "a2.i : " << a2.i << '\n';
return 0;
}
Output:
ubuntu@ubuntu-VirtualBox:~/Vaibhav_New$ ./Test8 A::A() A::~A() a2.i : 10 a2.i : 20 A::A() A::~A() a2.i : 30
In fun2()
, local object a1
is created and destroyed as function exits.
I returned the reference and playing with the object(a2.i).
Q1) Why am I able to do this?
When I call the fun2()
again, another object (old local object is already destroyed: destructor is called) is created and destroyed. I modified it (don't know how) as following:
fun2().i = 30;
Q2) Why is this affecting object a2
?
Earlier: a2.i : 20
Now: a2.i : 30
I'm not new to C++ but references are still mystery for me :(