I'm working with a dynamic vector class, called Vector. It has two attributes : longitud (which is the length) and p, which is a float pointer.
Here's the copy constructor :
1 2 3 4 5 6 7 8 9
Vector:: Vector(const Vector &v)
{
longitud = v.longitud;
p = newfloat[longitud];
for (unsigned i = 0; i<longitud; i++)
{
at(i) = v.at2(i);
}
}
The copy constructor seems to work properly, everything is fine when tracing it from inside. However, after the copy is finished and returnet, the first component of the copied vector, p[0] stores a weird value for no apparent reason (3.99294e-34).
The problem seems to be solved if i change line 4 to this
p = newfloat[longitud+1];
What is going on? What am i doing wrong?
Thanks in advance
Yeah, sorry about that helios. The copy constructor worked, but the whole thing isnt working properly. I'm a total newbie to C++,.. and consequently i'm terrible at things I used to know how to do in Free Pascal.
I really can't get where the error is. Im including the whole code (sorry for the lack of comments, they were in spanish, so i deleted them), just in case anything else is necessary. Go straight to the main() function. The problem is marked there.
Get rid of at2() and make at() const. float& at(unsigned i) const;
There are a few problems with your code.
The first is that operator*() unintuitively modifies one of the operands and doesn't have a return statement.
Some control paths in operator+() don't return anything.
By default, a vector should be constructed empty. If it's not, then its elements should be zeroed.
Your problem is that you've defined the copy constructor, but that's a constructor, which means it's only called when the object is defined. In this case, on line 116. On line 119 you return a temporary copy of a Vector which is immediately destructed after being assigned to c. Since you didn't overload operator=(), which is what will be called here, the default one will be called. The default operator=() only performs a shallow copy; for example, pointers are copied without doing any allocation. Once the returned object is assigned to c, it is deleted, so c.p is now invalid. The call on line 122 dereferences an invalid pointer, and when c is destructed after main() returns c.p is deleted a second time, messing even more with the heap.
Thank you so much helios. I think I'm in debt with you.
(by the way... i totally forgot about the operator*... i was gonna write down the operator overloading function, but went to the cafeteria and totally forgot about it. Also, thanks about mentioning about the paths in operator +)