Your operator+
receives copy of the argument passed to it.
CRectangle CRectangle::operator+ (CRectangle param) {
CRectangle temp;
temp.width = new int;
temp.height = new int;
*temp.width = *width + *param.width;
*temp.height = *height + *param.height;
return (temp);
}
In the code:
CRectangle a(3,4),b(5,6),c;
c=a+b;
More specifically, in the a + b
copy of b
is passed to a.operator+
. At the end of the function this copy is destroyed.
So, to sum up:
Now, your operator+
is receiving param
by value. This means that copy of object b
will be created and you will have two identical objects: b
and param
. When this function returns, param
object will be destroyed.
Now, everything would be good except:
Even b
and param
are separated objects, their pointers width
and height
points to a single memory location. Destructor of param
will free this memory and b
's pointers will point to deallocated memory locations. In order to prevent this, you need to write copy-constructor:
CRectangle::CRectangle(const CRectangle& param) {
width = new int; // alocate separate memory locations!
height = new int;
*width = *param.width;
*height = *param.height;
}
To avoid copy-on-passing, pass by const-reference instead:
CRectangle CRectangle::operator+ (const CRectangle ¶m)
As you noted, the same thing happens with operator=
.
Also, this code:
temp.width = new int;
temp.height = new int;
*temp.width = *width + *param.width;
*temp.height = *height + *param.height;
can be rewritten as (also the types of width
and height
should be changed to int
):
temp.width = width + param.width
temp.height = height + param.height;
There's no need to have pointers as fields in your class, if they serve just like regular values.