
Untitled
By: a guest on
May 4th, 2012 | syntax:
None | size: 1.36 KB | hits: 12 | expires: Never
returning a local as value/reference
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
class A
{
public:
int x;
string s;
A(int xx,string ss):x(xx),s(ss)
{
cout<<"A::A()"<<x<<","<<s<<"n";
}
A(const A& that)
{
cout<<"cpy ctrn";
x=that.x;
s=that.s;
}
A& operator=(const A& that)
{
cout<<"operator=n";
}
~A()
{
cout<<"~A()"<<s<<"n";
}
};
const A& getA1()
{
A a(1,"A1");
cout<<"returning from A1n";
return a;
}
A& getA2()
{
A a(2,"A2");
cout<<"returning from A2n";
return a;
}
A getA3()
{
A a(3,"A3");
cout<<"returning from A3n";
return a;
}
int main()
{
A &newA2 = getA2(); //.....................LINE 2
cout<<"returned from A2n";
cout<<"-----------------------------n";
A newA3 = getA3(); //......................LINE 3
//A const newConstA3 = getA3 ();
cout<<"returned from A3n";
cout<<"-----------------------------n";
//cout<<"newA2="<<newA2.x<<","<<newA2.s<<"n";
cout<<"newA3="<<newA3.x<<","<<newA3.s<<"n";
}
A::A()2,A2
returning from A2
~A()A2
returned from A2
-----------------------------
A::A()3,A3
returning from A3
returned from A3
-----------------------------
newA3=3,A3
~A()A3