Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
return reference to local variable
This is a sample program written for checking the scope of a local class object inside a function. Here I am creating an object of class A and assigning values to it and returns that object by reference in Function(). I want to know that when the scope of the variable will end?.Since it is a stack object(not pointer), Is it will be destructed in the end of the Function()? If so what will happen when its reference value is assigned to a new object?
#include "stdafx.h"
#include <iostream>
class A
{
public:
int a, b;
A(int aa, int bb)
{
a = aa;
b = bb;
}
A(){}
};
A& Function()
{
A object;
object.a = 10;
object.b = 20;
return object;
}
int _tmain(int argc, _TCHAR* argv[])
{
A aaa = Function();
std::cout<<"\nValue : "<<aaa.a<<" "<<aaa.b;
getchar();
return 0;
}
Undefined behavior is what happens!
A stack allocated object is local/automatic because all allocations of these objects are implicitly cleaned once the scope(
{,}) in which they reside ends.Returning reference to an local object is an undefined behavior.
Undefined behavior means literally any behavior can be seen. The program might work or it might crash or behave randomly. Just it is not a valid c++ program and anything can happen.