0

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
2
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Duoas
0

I don't know how you got that far...

You never initialize coeffs. You must set its length before playing with any elements. Or push elts onto the end.

Hope this helps.

0

You never initialize coeffs.

coefs is initialized in the initializer list of the constructor: Polynomial(int val = 0, int exp = 0) : [B]coefs(0, exp)[/B], degree(exp) Am I missing something? Thanks.

0

I figured it out. I was calling the std::vector constructor with the arguments reversed (as well as providing an incorrect initial size). The solution: Polynomial(int val = 0, int exp = 0) : coefs(exp + 1, 0), degree(exp)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.