class Point
{
private:
int x, y;
public:
.......
Point addition(Poin& p1)
{
int x1, y1;
x1 = this->x + p1.getX();
y1 = this->y + p1.getY();
Point res(x1, y1);
return res;
}
};
and I call addition from main:
1 2
Point p1(1, 2), p2(3, 4);
Point p3 = p1.addition(p2);
my question is: res in addition function is a local variable, after I get out from the scope of the function does this variable still exist? some explanation.
thanks.
No, it doesn't exist anymore, but it doesn't matter because you're returning a copy of it, anyway. You'd have a problem if you were to do this, though:
1 2 3 4 5 6 7
//Note modified return type:
Point &addition(Poin& p1)
{
//...
Point res(x1, y1);
return res;
}
can explain more,
** the '&' that u added is returning the address of the object that u created? isn't it? it its yes so I'm returning no copy of the created object.
thanks.
helios, if you mean returning a reference to the object that I constructed locally, so this would be not worth full because the object res will not exist after exiting from function.
I'm I right Or wrong?
thanks.
Correct. Returning a reference or pointer to a local object is illegal because it points to an object that is no longer there after the function returns.