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;
}