1

I am working on a C++ project that works with polynomials stored in a LinkedList. I want to overload important operators such as +, -, *, /. I had some issues with destructor when the function returns the result.

 Polynomial& Polynomial::operator+(const Polynomial &p){
    Polynomial  sum = *this;

    if (p.list.isEmpty())
        return *this;

    ListElement *temp = p.list.first;

    while (temp){
        sum.list.addSorted(temp->data);
        temp = temp->next;
    }

    return sum;
}

This function works very good, but return sum; calls the destructor and I lose the data. The destructor from Polynomial class calls list.purge(); which frees the dynamic memory in linked list. All the classes and its methods are good.

In main I have:

Polynomial p1,p2,sum;
p1.input();              //here I input data for first pol
p2.input();

sum=p1+p2;               //I overloaded operator=, it works fine

What I must do "to stop" the destructor? I want to output on screen Polynomial sum. Thank you!

3 Answers3

0

You SHOULD NOT return a reference to a local variable!

Polynomial  sum = *this;

...

return sum;

Remove the & from the return type. sum lives on the stack (aka in automatic storage). When its containing scope exits, it is destroyed-- the destructor for that instance is called. You should not return a reference to it; it's like returning a reference to a ghost.

If you return by value, a copy of sum will be returned and you will be OK.

Rob K
  • 8,757
  • 2
  • 32
  • 36
0

Don't return a reference to the local variable. Objects that are created within a function scope, live and die within that scope.

You can however, create variables which are references to objects, and the lifetime of that variable is now the same as the life time of the object it references.

Like this:

Polynomial& Polynomial::operator+(const Polynomial &p){
    Polynomial &sum = *this;

    if (p.list.isEmpty())
        return sum;

    ListElement *temp = p.list.first;

    while (temp){
        sum.list.addSorted(temp->data);
        temp = temp->next;
    }

    return sum;
}
smac89
  • 39,374
  • 15
  • 132
  • 179
  • `sum` is not NULL now and it is great, but I lose p1's data. I mean that : _p1=5X^2 p2=X^2_ after operator function _sum=6X^2_ **p1=6X^2** instead of 5X^2 p2=X^2 How to deal with this? – ursu.daniel2202d Jan 18 '17 at 14:30
0

It's better to overload operator + this way:

Polynomial operator+(const Polynomial& p1, const Polynomial &p2){
    if (p1.list.isEmpty())
        return p2;
    else if (p2.list.isEmpty())
        return p1;

    Polynomial sum = p1;
    ListElement *temp = p2.list.first;
    while (temp){
        sum.list.addSorted(temp->data);
        temp = temp->next;
    }

    return sum;
}

1. Let it have two parameters, and make it friend to class Polynomial

2. Return object instead of reference

zhm
  • 3,513
  • 3
  • 34
  • 55