I tried below C++ code
#include <iostream>
using namespace std;
int main()
{
int *p = new int;
*p = 10;
int &a = *p;
delete p;
a = 20;
cout<<a<<" ";
cout<<*p;
return 0;
}
and got output as: 20 20
I thought this may cause runtime error as result of accessing freed memory or some garbage. Probably I got this output as memory location freed by program may haven't been used so far so still retaining old values.
So I thought that it should also happen if I don't use references
#include <iostream>
using namespace std;
int main()
{
int *p = new int;
*p = 10;
// int &a = *p;
delete p;
// a = 20;
// cout<<a;
cout<<*p;
return 0;
}
but in this case I got output as 0 (checked with multiple runs). Does Reference has anything to do with different outputs?
Compiler: gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)