The default copy constructor should work for the Polynomial class below because it does not contain any dynamic data types. However, when I create a new Polynomial via the copy constructor, it prints 0 for the value of each coefficient. How can I fix this?
#include <iostream>
#include <vector>
class Polynomial
{
public:
Polynomial(int val = 0, int exp = 0) : coefs(0, exp), degree(exp)
{
coefs[exp] = val;
}
friend std::ostream& operator<< (std::ostream& os, const Polynomial& poly)
{
for (int i = poly.degree; i >= 0; i--) {
os << poly.coefs[i];
if (i > 1)
os << "t^" << i;
if (i == 1)
os << "t";
if (i != 0)
os << " + ";
}
return os;
}
protected:
std::vector<int> coefs;
int degree;
};
int main()
{
Polynomial p(5, 2);
std::cout << "p: " << p << std::endl;
Polynomial k = p;
std::cout << "k: " << k << std::endl;
return 0;
}
Output:
p: 5t^2 + 7t + 0
k: 0t^2 + 0t + 0