1
Polynomial& Polynomial::operator*(double k) {

    Polynomial result;
    Node<double>*current = first;
    if (!current) {
        throw "Can't do this operation with empty polynomial. /n";

    }
    
    for (int i = 0; i < length(); i++) {
        result.insertAt(i, k*current->info);
        current = current->next;
    }
    return result;
}

// The function insertAt() works correctly.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • Looks like you return a local variable by reference. That might be the problem. – Adomas Baliuka Oct 07 '20 at 12:04
  • 1
    Your compiler should be generating warnings about the following: [C++ Returning reference to local variable](https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable) – Botje Oct 07 '20 at 12:04

1 Answers1

3
Polynomial result;

A local variable called result gets defined in this function. Like all other local variables it will get destroyed, and will no longer exist, when this function returns. That's how local function variables work in C++.

return result;

This function is declared as returning a reference on object. This return statement returns a reference to result. However, by the virtue of returning from the function result gets destroyed at the same time. This function returns a reference to a destroyed object, and using this reference results in undefined behavior. This is the explanation for the anomalous behavior you're seeing.

This function should not return a reference, but should return the object by value. Hopefully Polynomial is fully Rule Of 3 compliant and has an appropriate copy constructor and an assignment operator, for this to happen correctly.

P.S. Most modern C++ compilers are fully capable of detecting this obvious, common bug. If your compiler issued diagnostic messages and warned you about it, this is a lesson to never ignore warning messages from your compiler, even if it successfully compiles your program. Your compiler wants to help you write correct code. Always verify that your program compiles without any diagnostic messages from your C++ compiler. A warning message from the compiler even if the program compiles wil indicate a real bug in your code more often than not.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148