From the code you've shown, it looks like coefficients
is probably a pointer initialized by the constructor Polynomial(int)
. From the behavior you describe, I'm certain enough of this that I'll answer your question even though you haven't shown the class.
Here's what it almost certainly looks like. Here I'll assume it stores int
values:
class Polynomial {
public:
Polynomial() : coefficients(nullptr), size(0) {}
Polynomial( int s ) : coefficients(new int[s]), size(s) {}
~Polynomial() { delete [] coefficients; }
int * coefficients;
int size;
};
And so now here is the problem. You have violated the Rule of Three by not providing a copy or assignment constructor for a class that manages its own memory.
When you do this:
for (int r = 0; r < size; r++){
pArray[r] = Polynomial(p.size);
}
Here is what happens:
- A temporary value is constructed by
Polynomial(p.size)
- The current
pArray[r]
value is destructed
- The assignment operator is invoked, which by default will trivially copy data members from the temporary directly into
pArray[r]
- The temporary value from step 1 is destructed.
Note step 4. You copied the pointer into another object, and then deleted that pointer. Now you have undefined behavior. In your case, what probably happened is that the call to new
always gave back the same pointer. That isn't guaranteed. Nothing is guaranteed when you have undefined behavior. But it does give away a strong hint that led me to write this answer.
To fix this, you must define a copy constructor for your object, which allocates a new coefficients
array and copies the data into that.
Polynomial::Polynomial( const Polynomial & p )
: coefficients( new int [p.size] )
, size( p.size )
{
std::copy( p.coefficients, p.coefficients+size, coefficients );
}
Or even better, store your coefficients in a std::vector
. You are using C++, after all. Then you don't need to worry about new, delete, copies, or moves (a concept which I have decided to omit from this answer).
If you must allocate, then at least store the pointer as a std::unique_ptr
-- that will then immediately give you a compile error when you attempt to copy your object, and force you to make a non-trivial copy constructor.