c++/5517: Internal variables in classes not stored correctly

rodrigc@gcc.gnu.org rodrigc@gcc.gnu.org
Mon Jan 28 16:38:00 GMT 2002


Synopsis: Internal variables in classes not stored correctly

State-Changed-From-To: open->closed
State-Changed-By: rodrigc
State-Changed-When: Mon Jan 28 16:38:33 2002
State-Changed-Why:
    This is not a bug in the compiler, but a bug in your program.
    
    Look at your mult() function:
    
    Polynomial Polynomial::mult(double num)
    {
      printf("Current polynomial is: ");
      this->print();
      Polynomial ans(degree);
      printf("Current polynomial is: ");
      this->print();
      int i;
     
      for (i=degree; i>=0; i--)
        {
          ans.coeff[i] = num * coeff[i];
          printf("coeff[i] is: %0.12lf\n", coeff[i]);
        }
      return ans;
    }
    
    
    Your are creating a Polynomial on the stack and then
    returning it.  But when the scope of the mult() function
    ends, the destructor will be called on ans!
    
    If you gave your class a Polynomial a copy constructor,
    and did something like:
       return Polynomial(ans);
    
    you would be OK.
    
    This is not a gcc bug.  Refer to a good C++ book,
    or ask questions on the comp.lang.c++.moderated newsgroup.

http://gcc.gnu.org/cgi-bin/gnatsweb.pl?cmd=view%20audit-trail&database=gcc&pr=5517



More information about the Gcc-prs mailing list