954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Default copy constructor

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
titaniumdecoy
Light Poster
37 posts since Mar 2007
Reputation Points: 68
Solved Threads: 4
 

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.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 
You never initialize coeffs.


coefs is initialized in the initializer list of the constructor: Polynomial(int val = 0, int exp = 0) : <strong>coefs(0, exp)</strong>, degree(exp)


Am I missing something? Thanks.

titaniumdecoy
Light Poster
37 posts since Mar 2007
Reputation Points: 68
Solved Threads: 4
 

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)

titaniumdecoy
Light Poster
37 posts since Mar 2007
Reputation Points: 68
Solved Threads: 4
 

You got it.

Duoas
Postaholic
2,043 posts since Oct 2007
Reputation Points: 1,140
Solved Threads: 229
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You