Hey everyone,

I'm very new to c++ and need some help with overloading operator= for a polynomial class. Here's my relevant code:

// i can't change the method signature as it is required this way
polynomial& polynomial::operator =(const polynomial& rtSide) {
	
	this->nullify(); // a method to reset variables

	polynomial result;
        // the degree method returns the degree of the polynomial
        // set coefficient method sets coefficient of the given exponent
	for (int i = 0; i <= rtSide.degree(); i++)
		result.setCoefficient(i, rtSide.coefficients.at(i));

	return result;
}

the code in my main method

polynomial * polynomials = new polynomial[NUM_POLY]; // NUM_POLY = 5;

//initialize the polynomials 
for (int i = 0; i < NUM_POLY; i++)
	polynomials[i].nullify();
.
.
.

// the code before this builds up the polynomials based on user input from command line
int i = 1; int j = 0;
polynomials[i] = polynomials[j]; //this is not working for some reasons; the polynomials[i] remains the same as it is before but the line below works

//polynomial p = polynomials[j];

I'm new to this and can't seem to pin point the problem even after wasting more than 3 hours on this. I would really appreciate if someone can guide me to the solution, thanking in advance.

Dani AI

Generated

A few clarifications and a robust pattern to make this assignment safe and simple.

As pointed out, your original routine built and returned a temporary instead of updating the object on the left-hand side — and returning a reference to a local object is undefined behavior. That explains why polynomials[i] = polynomials[j] behaved oddly. is also right to worry about self-assignment and consistency between how you access coefficients and how you modify them.

A recommended, compact and exception-safe implementation is the copy-and-swap idiom. It makes self-assignment a non-issue, gives the “strong” exception-safety guarantee, and is easy to reason about:

// lightweight swap that only touches member state
void swap(polynomial &a, polynomial &b) noexcept {
    using std::swap;
    swap(a.coefficients, b.coefficients);
    swap(a.degree, b.degree);
}

// operator= makes a copy first, then swaps
polynomial& polynomial::operator=(polynomial rhs) {
    swap(*this, rhs);
    return *this;
}

Notes and troubleshooting checklist

  • If coefficients is a std::vector (preferred), letting vector copy or swapping it is correct and cheap. If you use raw pointers or manual heap arrays, implement or fix the copy constructor, destructor and assignment operator (Rule of Three/Five) to avoid shallow copies or leaks.
  • Do not call nullify() in a way that invalidates rtSide’s data; nullify should only reset this object’s state.
  • For debugging, temporarily log from the assignment operator or put a breakpoint to confirm it’s being called and inspect coefficients.size() and degree after assignment.
  • Keep access consistent: either use the container directly (e.g. coefficients = other.coefficients) or only use setCoefficient/getCoefficient, but avoid mixing patterns that can leave degree out of sync.

These points extend the earlier answers and give a safe, maintainable implementation path.

Recommended Answers

All 5 Replies

Your function is creating a polynomial and modifying that. It is not modifying the object on which it was called.

Your latter example, polynomial p = polynomials[j]; , actually calls the copy constructor to initialize p. The other plausible alternative would for a zero-argument constructor to be called to initialize p, and then for operator= to be called. But that typically would be slower, so instead the C++ guys decided that using assignment syntax to initialize a variable would call the constructor.

^thanks for the quick reply; I get what you're saying. Does the following code look ok because it seems to be doing the trick:

polynomial& polynomial::operator =(const polynomial& rtSide) {
	
	this->nullify();

	for (int i = 0; i <= rtSide.degree(); i++)
		this->setCoefficient(i, rtSide.coefficients.at(i));

	return *this;
}

thanks for the help

I don't know what nullify does, but it looks right.

How are you handling the zero polynomial?

^I'm required to simply return it as 0x^0.

btw thanks for your help, it saved me load of trouble

Please note that the code you have is 99% wrong.

Consider

Polynominal A;
A=A;

And before you say you would never do that, be very very careful of compiler opimization, double loops that i=j (e.g. for(int i=0;i<N;i++) for(int j=0;j<N;j++) and many other places.

You should write FOR EVERY operator= (-- with a MINIMUM of a paragraph of comment if you break the rule) this:

Polynomial&
Polynomial::operator=(const Polynomial& A)
{
    if (this!=&A)
      {
          // coping stuff
      }
    return *this;
}

Additionally, since you are actually in the class I stronly suspect that you don't need the

for (int i = 0; i <= rtSide.degree(); i++)
		this->setCoefficient(i, rtSide.coefficients.at(i));

which is ugly since you use setCoefficients but access coefficient directly.

but rather just

coefficients=rtSide.coefficients;

you might need to add a little index/other parameter control etc
but it is likely to be much quicker AND much less error prone.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.