So for a task for school, I have to create a type class that can handle large ints stored as a dynamic array of shorts. I have hit a snag on the addition operator though. I want to be able to add them like obj = obj1 + obj2. The object arrays are size 40 and the numbers are stored like {0,0,0,0....,1,2,3,4}. So if I added obj1 and obj2{0,0,0...,0,1} I would get {0,0,0,0.....,1,2,3,5}. I have attached what code I came up with, it complies but just gives a overflow error when I get to that part of the program
1 2 3 4 5 6 7 8 9
myInteger operator+(const myInteger& obj)
{
myInteger temper;
for (auto i = 0; i < arrSize; i++)
{
temper.ptr[i] = ptr[i] + obj.ptr[i];
}
return temper;
}
You didn't show the default constructor for your myInteger class, but my guess is that it, by default, is not allocating enough space for the temp.ptr array. In other words, what is temp.arrSize? Does it equal this->arrSize? How is temper.ptr being initialized?
arrSize is a static array size 40, that's used in the constructors. I have attached my constructor below. bigness is a private member that holds the length of the int inside the array.
That constructor takes one argument, so it can't be the same constructor as in your first post (unless there's a default argument in the prototype in a header file, I guess).
You are going beyond array bounds with i<= arrSize in this latest post. This will cause buffer overflow.
Also, your addition operator doesn't see to have any concept of a "carry" operation, and it would make more sense to store your number from index 0, not the last index as your constructor implies. You can always write your array elements in reverse order when you want to actually output the number.