Simplifying: I am trying to write a simple Polynomial
class and I get incorrect values when I try to overload the multiplication operator:
#include <iostream>
class Polynomial {
public:
unsigned int degree;
int *coefficients;
Polynomial(unsigned int deg, int* arr) {
degree = deg;
coefficients = arr;
}
~Polynomial() {}
int& operator[](int index) const {
return coefficients[index];
}
};
std::ostream& operator<<(std::ostream &os, const Polynomial& P){
for (unsigned int i=0; i < P.degree; i++) os << P[i] << ",";
os << P.coefficients[P.degree];
return os;
}
Polynomial operator*(const Polynomial &P, const int &x) {
int arr[P.degree];
for (unsigned int i=0; i <= P.degree; i++) arr[i] = P[i];
Polynomial p(P.degree, arr);
std::cout << p << std:: endl; // just for debugging
return p;
}
I am testing the code in my main
:
int g[] = {-1, 0, 1, 1, 0, 1, 0, 0, -1, 0, -1};
Polynomial P_g = Polynomial(10, g);
std::cout << P_g << std::endl;
Polynomial P_g_3 = P_g*3;
std::cout << P_g_3[0] << std::endl;
std::cout << P_g_3[1] << std::endl;
std::cout << P_g_3[2] << std::endl;
std::cout << P_g_3[3] << std::endl;
std::cout << P_g_3[4] << std::endl;
std::cout << P_g_3[5] << std::endl;
std::cout << P_g_3[6] << std::endl;
std::cout << P_g_3[7] << std::endl;
std::cout << P_g_3[8] << std::endl;
std::cout << P_g_3[9] << std::endl;
std::cout << P_g_3[10] << std::endl;
std::cout << P_g_3 << std::endl;
But the output in the console is something totally different then what I expect:
-1,0,1,1,0,1,0,0,-1,0,-1
-1,0,1,1,0,1,0,0,-1,0,-1
-1
0
0
0
0
0
-2002329776
32767
-516177072
32766
539561192
0,32766,539581697,32767,-2002329776,32767,1,0,243560063,1,-2002329776
Although notice that the inner cout
statement from within the overloaded operator returns a correct polynomial. Only when the program exits that function the coefficients get screwed... Moreover the two printing strategies are not even consistent with themselves. What is going on?