Contrary to your source comments, the class p2dArray has no proper copy constructor(s). You define (wrong) assignment operator but don't define explicit copy constructor. A copy constructor must have (as usually) the signature:
p2dArray::p2dArray(const p2dArray&);
No such member declared in your class but default copy contructor (copy member by member) is inadequate to the dynamic nature of the contents pointer member. However return temp2d; statement in operator+ needed a copy constructor. Inadequate default copy constructor copies temp2d.contents pointer to the result matrix then temp2d object is destructed. Now result object has a pointer to deallocated memory.
That's a brief story.
Yet another remarks:
- The class has inadequate default constructor. It does not initialize members and you get unpredictable pointers and dimensions in constructed objects.
- The operator= does not check target dimensions.
Moral: feel the difference between assignment op and copy constructor...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
I see you did not feel the difference ;)...
An assignment operator has a valid, initialized target object. It changes the contents of this object. A copy constructor has raw memory chunk (the same as any other constructor). It must build the object with the same content as its argument from the scratch. Alas, your copy constructor starting from the deallocation of never allocated memory (and the program gets memory exception, of course).
Look at your new copy contructor body. You delete previous contents - but NO any previous contents here! You must allocate memory for this new matrix (see p2dArray(int,int) constructor) then copy argument's data to this allocated 2-d array.
In the new default constructor you forgot to initialize the most sensitive member: the contents pointer. Therefore the constructed (empty) object has garbage valued pointer (instead of the valid null pointer). Now let's look at the class destructor. What happens when it will try to destruct an empty object with unpredictable garbage value of the contents member? Right, it will try to deallocate this "pointer to nowhere"...
It's up to you...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348