A method;
Sterling operator+(const Sterling& o) const {
return Sterling(*this) += o;
}
Does this line “Sterling(*this) += o” create a new Object in stack memory? If true, how can it return an object in the stack to outside the method?
Can I do like this:
Sterling operator+(const Sterling& o) const {
return *this += o;
}
because I think *this is an object so we don’t need to create a new Object?
Creates object on the stack, but you don’t actually return this object, you return a copy of it. This function does:
operator+=of the temp object withoSterling operator+(const Sterling& o) const– if it wasSterling& operator+(const Sterling& o) const( *note the&* ), then this would be a problem )Anyway, your compiler could optimize this and avoid copying of the local object, by using RVO
And the second question:
This is different from the first one – the first case creates temp object and changes it, then returns it. If you do the second, this will change
thisand then return copy of it. But note,thisobject is changed!So, the summary – both return the same result, but the second changes
this. (his would be useful, if you want to overloadoperator+=, notoperator+)