I'm trying to set up the overloaded operator '=' for a custom Array class for practice, but it seems to be causing a runtime error.
class Array {
private:
static int numberOfElements; //class static variable
int size;
int* numbers;
public:
Array(int);
Array(const Array&);
~Array();
int getSize();
static int getNumberOfElements();
Array& operator =(const Array&);
};
This overloaded operator function produces the correct output, but with a runtime error:
Array& Array::operator =(const Array& newArray) {
numberOfElements = numberOfElements - size + newArray.size;
size = newArray.size;
for (int i = 0; i < size; i++)
numbers[i] = newArray.numbers[i];
return *this;
}
Before, I had
Array& Array::operator =(const Array& newArray) {
delete[] numbers;
numberOfElements = numberOfElements - size + newArray.size;
size = newArray.size;
numbers = new int[size];
for (int i = 0; i < size; i++)
numbers[i] = newArray.numbers[i];
return *this;
}
Which does not produce a runtime, but creates an array filled with garbage. numberOfElements is just tracking the total elements in all Arrays, and shouldn't be a factor in the error. I'm certain the issue is the dynamic allocation, but I can't seem to logically figure out why it would throw a runtime if I'm only overwriting the original array with newArray, and why the latter is filling with garbage even though the allocated array is being set to newArray's elements.