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

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.

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.

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)

You got it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.