There are many things wrong with your code. One of the is that you haven't defined a copy constructor but you are returning an object (*this
) by value from your assignment operator. I would guess that the "copied" object points to something funny and the access to this pointer results in undefined behavior.
That said, I'm puzzled how anybody can cope with the complexity of the assignment operator! Your assignment operator has more problem:
- It leaks memory if the object is actually pointing a actually allocated memory.
- It wouldn't do too well with self-assignment.
Personally, I'm having trouble implementing assignment operators unless they leverage the copy constructor, destructor, and swap()
function (of course, I'm only programming with C++ since nearly 25 years so maybe I'll figure it out at some point). The swap()
may not exist, yet, but should implemented anyway:
polynom& polynom::operator= (polynom other) {
this->swap(other);
return *this;
}
void polynom::swap(polynom& other) {
std::swap(this->grad, other.grad);
std::swap(this->arr, other.arr);
}
Of course, this assumes you have a working copy constructor.
Here are other random problem:
- As mentioned, the copy constructor needs a proper implementation.
- In your assignment operator you don't verify if the right hand side
polynom
has a non-NULL
pointer inarr
but your default constructor initializes thearr
member toNULL
. - The
using namespace std;
should be after including a standard header, not before. Of course, headers should have ausing
-directive at all! At least in headers your are much better off using full qualification, e.g.,std::ostream
. - This one isn't quite a problem but a bit nitpicking: you shouldn't include
<iostream>
in headers unless you usestd::cout
,std::cin
,std::cerr
, orstd::clog
! I would include<iosfwd>
in the header and<ostream>
in the implementation and only<iostream>
where things are actually written.
(I had claimed that there was another problem with just storing pointers to arrays but that's not the code; I removed it from the list; sorry).