C
cppaddict
I'd like to know what goes on under the hood when methods return
objects. Eg, I have a simple Point class with two members _x and _y.
It's constructor, copy constructor, assignment operator and additon
operator (which returns another Point object, and which my question is
about) are as follows:
Point:oint(int x, int y) :
_x(x),
_y(y) { }
Point:oint(const Point& p) {
_x = p._x;
_y = p._y;
}
Point& Point:perator=(const Point& p) {
_x = p._x;
_y = p._y;
return (*this);
}
Point Point:perator+(const Point& p) const {
Point ret(_x + p._x, _y + p._y);
return ret;
}
What happens when operator+ returns the temporary Point object that it
creates?
Does it use the copy constructor to create a copy of the temporary
variable "ret"? Is ret destroyed after that?
If not, how does it return a Point object?
Also, why is that "new" never comes into play? How can the compiler
know beforehand how many Point objects will be created via operator+?
Is it because such objects must exist in statements like:
Point p3 = p1 + p2;
I know this is a simple point, but I'm confused nonetheless.
Thanks for any clarification,
cpp
objects. Eg, I have a simple Point class with two members _x and _y.
It's constructor, copy constructor, assignment operator and additon
operator (which returns another Point object, and which my question is
about) are as follows:
Point:oint(int x, int y) :
_x(x),
_y(y) { }
Point:oint(const Point& p) {
_x = p._x;
_y = p._y;
}
Point& Point:perator=(const Point& p) {
_x = p._x;
_y = p._y;
return (*this);
}
Point Point:perator+(const Point& p) const {
Point ret(_x + p._x, _y + p._y);
return ret;
}
What happens when operator+ returns the temporary Point object that it
creates?
Does it use the copy constructor to create a copy of the temporary
variable "ret"? Is ret destroyed after that?
If not, how does it return a Point object?
Also, why is that "new" never comes into play? How can the compiler
know beforehand how many Point objects will be created via operator+?
Is it because such objects must exist in statements like:
Point p3 = p1 + p2;
I know this is a simple point, but I'm confused nonetheless.
Thanks for any clarification,
cpp