Bit of trouble with overloading assignment operator (=)

Hello. I'm trying to get my class/object to able to work with code like

c = a + b

The problem I'm having is that my overloaded operator (=) seems to work fine in assigning simple values (like ints/doubles and the ilk), but fails in copying a dynamic array in each object. The array that is in the being operated upon contains garbage after the function executes.

I'm not exactly sure where the problem lies. In my implementation of the overloaded addition operator (+), the temporary object I create and return is fully accurate. And the fact that simple variables (i.e int a,b,c,d,etc) are correct, but the array in the object is not, confuses me.

My class is simply a Polynomial object that is supposed to keep track of the degree of the polynomial equation and store the coefficients in a dynamic array.

Here's a brief snippet of the header for the class.

1
2
3
4
5
6
7
8
9
10
11
12
class Polynomial
{
public:
Polynomial();
~Polynomial();
Polynomial operator + (const Polynomial & other) const;
Polynomial & operator = (const Polynomial & b);
private:
int myDegree;
int * myCoef;
int mySize;
};


And of the "=" operator function. Simply scrolls through the array and copies the values over. Also does all the other values. I just left it out for brevity.

1
2
3
4
5
6
7
8
9
10
Polynomial & Polynomial::operator = (const Polynomial & b)
{
	mySize = b.mySize;

	for(int i = 0; i < mySize; i++)
		myCoef[i] = b.myCoef[i];


	return *this;
}


Assuming that the overloaded "+" operator is correct (which seems true from all my testing and displaying at various points in the function), could there be a problem with the way dynamic arrays/pointers to dynamic arrays are handled here?
Assignment operators typically make sure they are not assigning *this to *this. Also note that the sizes of the array might not be the same--which is probably resulting in a memory leak or buffer over-run. Also verify that the copy constructor does a deep copy.

Please post your copy constructor, operator+, and destructor methods.
Last edited on
OP here.

I've figured it out. I didn't have a copy constructor and only had the assignment operator overloaded. Bah!

I didn't know a call to the copy constructor is made during something like:

object a,b;

a= b + a;

Thanks for the help! I went off and made the copy constructor after you mentioned it, heh. It still confuses me a bit on why the call to the constructor is made, however, and why it's not just calls to the overloaded operators...
Last edited on
Topic archived. No new replies allowed.