Why doesn't destructor work?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nammae
    New Member
    • Dec 2009
    • 3

    Why doesn't destructor work?

    Hello! I have a code:
    [CODE=C++]
    // class Polynomial
    // Constructor, Destructor
    // Friend Function, Operator Overloading
    #include <iostream.h>

    class Polynomial
    {
    private:
    int n; // Degree of polynomial
    double* p; // Pointer to array contains
    // coefficients of polynomial

    public:
    Polynomial();
    Polynomial(int n1);
    ~Polynomial();

    friend ostream& operator<< (ostream& os, const Polynomial& pol);
    friend istream& operator>> (istream& is, Polynomial& pol);

    // plus two polynomials
    Polynomial operator+ (const Polynomial& daThuc2);
    };

    Polynomial::Pol ynomial()
    {
    this->n = 0;
    this->p = NULL;
    }

    Polynomial::Pol ynomial(int n1)
    {
    this->n = n1;
    this->p = new double[n1+1];
    if(NULL == p)
    {
    cout << "Not enough memory.";
    exit(1);
    }
    }

    Polynomial::~Po lynomial()
    {
    this->n = 0;
    delete this->p;
    }

    ostream& operator<< (ostream& os, const Polynomial& pol)
    {
    os << "Coefficien ts of the polynomial( from ao ): ";
    for(int i = 0; i <= pol.n; ++i)
    os << pol.p[i] << " ";
    os << endl;
    return os;
    }

    istream& operator>> (istream& is, Polynomial& pol)
    {
    cout << "Enter degree of polynomial: ";
    is >> pol.n;
    pol.p = new double[pol.n+1];

    cout << "Enter coefficients of the polynomial( from ao ): ";
    for(int i = 0; i <= pol.n; ++i)
    is >> pol.p[i];

    return is;
    }

    Polynomial Polynomial::ope rator+ (const Polynomial& pol2)
    {
    int n1 = n > pol2.n ? n : pol2.n;
    Polynomial polSum(n1);
    int i = 0;
    while(i <= n1)
    {
    if(i <= n && i <= pol2.n)
    polSum.p[i] = p[i] + pol2.p[i];
    else if(i <= n)
    polSum.p[i] = p[i];
    else
    polSum.p[i] = pol2.p[i];
    ++i;
    }

    i = n1;
    while(i > 0 && 0 == polSum.p[i])
    --i;
    polSum.n = i;
    return polSum;
    }

    int main()
    {
    Polynomial f, p, q;

    cout << "Enter polynomial p:\n";
    cin >> p;
    cout << "Enter polynomial q:\n";
    cin >> q;

    f = p+q;
    cout << "Polynomial f:\n";
    cout << f;

    return 0;
    }
    [/CODE]
    Why does this code run normally?
    I think when method "operator+" finishes, the memory which is allocated to polSum will be deallocated by the destructor automatically.
    But in this case when I try to compile it, it runs normally. The polynomial f is equal to sum of two polynomial p and q.
    In addition, why if I try to change type of p( pointer to array contains coefficients of polynomial ) to int, the result become wrong?
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    It's deallocated, but before that it's copied by 'return' statement to return value of the same type and then assigned to f in main().

    Comment

    • nammae
      New Member
      • Dec 2009
      • 3

      #3
      Thank you very much.
      But I still don't understand: if the memory which contains coefficients of polynomial is deallocated, why is the result is exact?

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        I think you have undfined behaviour. The internal array is deallocated and since you use the member by member default copy constructor and assignment operator. By the end of main f.p ends up with the same value as polSum.p but polSum.p is deleted as polSum is destructed so f.p ends up pointing to unallocated data. You then access this pointer causing undefined behaviour.

        Once you have invoked undefined behaviour all bets are off, anything could happen including getting the results you expected from working code as you have got. However needless to say if you leave the code like this in the end it will go wrong.

        You need to implement a copy constuctor and an assignment operator for this class to ensure it copies memory correctly.

        Finally on a point of style it is often considered best practice to implement operator+= and then implement operator+ in terms of operator+=, again a copy constructor or operator= is required. For any class T implementing operator+= operator+ is
        Code:
        T T::operator+(const T& rhs)
        {
            return T(*this) += rhs;
        }
        It means you only have to implement and support the addition algorithm once.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Problems like this occure due to using a pointer as a member variable and passing to various functions that fiddle with memory. The is usually a recipe for disaster.

          I suggest you use a handle class: http://bytes.com/topic/c/insights/65...-smart-pointer

          Comment

          • nammae
            New Member
            • Dec 2009
            • 3

            #6
            @everyone: Thank you very much.

            Comment

            Working...