How to get Operator + return a dynamic object.?

I'm overloading the sum of two vectors. "Vector" is a class that works as a dynamic vector. I'd like to know if it is possible to get a new object-Vector as output from this overload (of course, i don't want to do it the cheap way : modifying any objects that are part of the sum).

This is the only thing i can think ok

Vector Vector::operator + ( Vector &a)
{
if (a.length() == length())
{
Vector temp(a.length());
for (int i = 0; i < a.length(); i++)
{
temp.at(i) = (a.at(i)+at(i));
}
return temp;
}
else
{
cout << " +ERROR : Vectors have different lengths " ;
}
}

However, temp is only declared in the operator overload scope, so after the return, temp's destructor is invoked and i'm returning an object that will no longer exist.

Any ideas?
Thanks in advance
Last edited on
No. You're retuning the copy of an object that no longer exists. to draw a parallel, when you return an int, you don't have to worry about the variable you're returning going out of scope, because the very act of retuning it copies it.
If I'm not mistaken, when you return an object it will return a copy of it, so although the one used in the function goes out of scope, you can still return it. It only matters if you are returning a reference to an object that will go out of scope.

I may be wrong though.

Edit: Beaten to it by helios, but at least now I know I wasn't wrong.
Last edited on
First of all, thanks for the fast reply!.
About both replies :

The class vector contains two variables : longitud (which stores the length) and p, which is a float pointer. If I return a copy of temp, it'll return an object that points to the same memory direction temp pointed to. However, when temp goes out of scope, the destructor is invoked, and the memory it pointed is deallocated because of its destructor. Now, the copy of temp is pointing to a memory zone which is not reserved (if i'm not mistaken).... and that messes things up.

Is there any clean way to sort this out?
Last edited on
In that case, you should make the copy constructor do a deep copy of the object. Instead of copying the pointer from the original object, the new object should allocate its own array and memcpy() the contents from the original or call the copy constructor for the type for each element.
Last edited on
Sounds great. Thanks a lot. When I get to try it, I'll mark this as solved. Once again, thanks a lot.

EDIT : It works great!!
Last edited on
Topic archived. No new replies allowed.