Quick question on returning references to local variables
My question is , in the code below , how is it that the last ob1.show
() displays 15 50, even though the temp object in overloaded operator
function has been destroyed as illustrated by the destructor call.
If the temp object has been destroyed then how come ob1 gets the
updated values:
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {
cout <<"In argument less constructor"<< endl;
longitude = 0;
latitude = 0;
}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
cout << "In the constructor with arguments " << longitude <<" " <<
latitude << endl;
}
~loc () {
cout << " In Destructor " << longitude << " " <<latitude << endl;
}
void show() {
cout << longitude << " ";
cout << latitude << "\n";
}
loc& operator+(loc op2);
};
// Overload + for loc.
loc& loc::operator+(loc op2)
{
cout << "In operator before temp" << endl;
loc temp;
cout << "In operator after temp" << endl;
temp.longitude = op2.longitude + longitude;
temp.latitude = op2.latitude + latitude;
return temp;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1.show(); // displays 10 20
ob2.show(); // displays 5 30
ob1 = ob1 + ob2;
ob1.show(); // displays 15 50
//system("pause");
return 0;
}
Output
~~~~~~~~~
In the constructor with arguments 10 20
In the constructor with arguments 5 30
10 20
5 30
In operator before temp
In argument less constructor
In operator after temp
In Destructor 15 50
In Destructor 5 30
15 50
In Destructor 5 30
In Destructor 15 50
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]