I’m writing an generic Array class and overloading operators for convenience. I’ve gotten my Array<> object to hold other Array<> objects, but I’m having trouble overriding the * operator. I need to copy the left object, so my operator* code is this:
Array<T>& operator*(const double scalar) {
return Array<T>(*this) *= scalar;
}
(operator*= has been overloaded and works).
I overrode the copy constructor as below:
UPDATE: New copy constructor:
Array<T> (const Array<T>& copyfrom) {
size_=copyfrom.size();
data=new T[size_];
copy(©from.data[0], ©from.data[size_], data);
}
My thought is that if the array were not generic but always filled with a primitive, this code would work. But I think there’s something going on here because I’m using a template that’s causing behavior I don’t expect. The data array in the new “deep copied” Array acts like it’s just a shallow pointer copy of the “copyfrom” data array.
How do I made this copy constructor work for both primitives and objects, using templates? Or, better yet, is there a way to overload operator* without worrying about copy constructors? Thanks.
EDIT: Here is the code for operator*=. I still think my problem lies in my use of the copy constructor, however.
Array<T>& operator*=(const double scalar) {
for (int i=0; i<size_; i++)
data[i]*=scalar;
return *this;
}
EDIT: I realized that I was getting problems because I was ignoring the size of my inner arrays in my array of arrays. Things are more reliable now. Everyone’s been really helpful, and I think I’m on the way to making this work. My operator= (which I hadn’t overloaded; good catch, Michael) is now as below. It acts as expected, but I’m starting to get malloc errors in my program and I’m exploring why. Is there anything wrong with the memory management here?
Array<T>& operator=(const Array<T>& a) {
if (this==&a)
return *this;
delete [] data;
size_=a.size();
data=new T(size_);
copy(&a.data[0], &a.data[a.size()], data);
return *this;
}
EDIT: I fixed the malloc errors! My methods are all working as intended now. The memory problems were coming because I had this method header:
template <typename T>
static Array<T> matrixSolve (Array<Array<T> > m);
I was taking an array of arrays by value. All sorts of problems. Took the array by reference and everything worked out. Thanks for the help, everyone!
You’ll want your operator* member function to look something like this:
If you return an
Array<T> &, then you will be returning a reference to a temporary which will be destroyed, causing undefined behavior.