title: C++ - Array values in class member function changing spontaneously
body: <p>I'm having some issues overloading the *= operator in my polynomial class. I've included all I believed relevant to solving the problem below. I apologize for the length of the code.  </p>
  
  <p>Here are the parts of my class header I think are relevant.</p>
  
  <pre><code>#ifndef POL_H
  #define POL_H
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;cmath&gt;
  
  using namespace std;
  
  class Pol
  {
    // private data members
  
    string polname;  // polynomial name
    int degree;      // polynomial degree
    int *coef;       // array with polynomial coefficients
  
   public:
  
    //  constructors
  
    Pol(string, int, int*);         // with input name, degree 
                                    // and array of coefficients
    // operator overloading
  
    Pol operator *= (Pol);
  
    //  other methods
  
    void PrintPol ();
  </code></pre>
  
  <p>Here is my .C file with the overload of *=. I decided not to include the PrintPol method as it is very long and I'm almost 100% sure the problem does not lie with it.</p>
  
  <pre><code>#include "Pol.h"
  
  Pol::Pol (string s, int d, int *c)
  {
    degree = d;
    polname = s;
    coef = new int [degree + 1];
    coef = c;
  
    // initializes polynomial of degree d with c coefficients
    // named s
  }
  
  Pol Pol::operator *= (Pol p1)
  {
    int *cp = this-&gt;coef; // If I print the values stored in cp at this point 
                          // everything is alright
  
    for (int i = p1.degree; i &gt;= 0; --i)
      {
        for (int j = this-&gt;degree; j &gt;= 0; --j)
      {
        this-&gt;coef[i + j] += p1.coef[i] * cp[j];
        cout &lt;&lt; cp[j] &lt;&lt; endl; // When I print the values here, they've changed!
      }
      }
  
    this-&gt;degree += p1.degree;
  
    return *this;
  }
  </code></pre>
  
  <p>My first thought was that maybe I was overstepping the bounds of the array, but the size of the array cp I create is this->degree, and that is also the highest value that "j" assumes, so I think that can't be it.</p>
  
  <p>Here is just my main function. I doubt the problem is here, but I included it anyway, so you could see how I'm using the methods I've declared.</p>
  
  <pre><code>#include "Pol.h"
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int main ()
  {
    int a [9] = {0, 0, 2, 4, 0, 0, 5, 0, 1};
    int b [5] = {4, -2, 0, 0, 1};
  
    Pol P2 ("P2", 4, b);
    Pol P4 ("P4", 8, a);
  
    P4*= P2;
    P4.PrintPol();
  
    return 0;
  }
  </code></pre>
  
  <p>This is probably really obvious and I'm just making an ass out of myself, but I've staring at the code for hours and I can't figure it out. Thanks in advance.</p>