I am trying to create a Polynomial class, whose representation is a dynamically allocated 2D array (stored in data member int** arrPtr
). The assignment operator for the class is problematic, as the delete operator throws the exception only when I use the assignment operator.
I set up some print statements in my code and learned that the coefficients and exponents of the argument polynomial are successfully copied into the target polynomial despite the error.
Here is the constructor, destructor, and assignment operator definitions (I'm also providing getCoefficient()
since I used it in the assignment operator definition):
#include "Polynomial.h"
#include <stdexcept>
#include <iostream>
Polynomial::Polynomial(int degree) : degree{ degree } {
arrPtr = new int* [2];
for (int i{ 0 }; i < 2; i++) {
arrPtr[i] = new int[degree + 1]{};
}
for (int i{ 0 }; i <= degree; i++) {
arrPtr[1][i] = i;
}
}
Polynomial::~Polynomial() {
for (int i{ 0 }; i < 2; i++) {
delete[] arrPtr[i];
}
delete[] arrPtr;
}
Polynomial& Polynomial::operator=(Polynomial polynom) {
for (int i{ 0 }; i < 2; i++) {
delete[] arrPtr[i];
arrPtr[i] = new int[polynom.degree + 1];
}
degree = polynom.degree;
for (int i{ 0 }; i <= degree; i++) {
arrPtr[0][i] = polynom.getCoefficient(i);
arrPtr[1][i] = i;
}
return *this;
}
int Polynomial::getCoefficient(int term) {
if (term <= degree) {
return arrPtr[0][term];
}
else {
throw std::out_of_range("Term exceeds the degree of the polynomial.");
}
}
EDIT: Thanks for the vivid response, everyone. This was a newbie mistake, not defining a copy constructor, which I did, and everything works now. I guess I won't be forgetting the Rule of Three anytime soon.