Posted on 2003-11-05
I found myself overloading the + operator for the first time today for a class that I'm writing. But I quickly realized that there appears to be an inherent problem with overriding the + operator for user-defined types.
myclass a = "hey";
myclass b = " there";
c = a + b;
This is equivalent to:
c.operator=( a.operator+( b ) );
The + operator allocates a new "myclass" object, initializes it to the sum of 'a' and 'b', and then returns it. Then that temporary object is assigned to 'c'. But no one ever deletes the temporary 'myclass' object that the + operator created!
What is the solution? How is this typically implemented?