Where and when do you get that error?
The only actual problem I can see is that you didn't provide an assignment operator, so the compiler will provide it's own, and that one will simply copy all members, including the pointers. This default assignment operator will be called in this line:
sum = p + p2;
The problem here is that now this will happen:
1.
operator+
will create a new, temporary
Polynomial
object
2. The default assignment operator will copy all data from that temporary object to
sum
, including the
pointers factor
and
power
.
3. The temporary object will be destroyed, and therefore its arrays
power
and
factor
will be deleted.
4. Now
sum.factor
and
sum.power
point to invalid memory!
5. the call to
sum.Print()
will likely fail
6. Even if not, once the program exits,
sum
will be destructed, trying to
delete[]
power
and
factor
, causing a runtime error.
Solution: Create your own assignment operator that actually copies the arrays rather than the pointers.
There's also another issue in the implementation of
operator+
: you are assuming that the two operands have (no more than) 3 terms, and that these terms have corresponding values for power. Either you drop power from your data structure entirely and just save your 'factor's in a predefined order, or else you
must compare the power values and up only the corresponding ones,
and you must consider the possibility that upon adding two polynomials with 3 factors each, the resulting polynomial might need to store up to 6 factors!