Your original version is actually the correct one. You create a temporary String object inside your operator+ function and return it by value to the caller. In the function return code, the value will be copied to another temporary string on the stack and then via the assignment operation that value will be copied to your variable z. (Don't worry, the compiler can optimize a lot of this copying away for you.)
What's probably not correct is the way in which you implemented the copy constructor and assignment operators. If you are not receiving the correct value in z, then look into these functions; you may also show us the code of them by using the green "Improve Question" button, so we can give you a little help with that.
Now to your alternative code:
String operator + (const String& other) const
{
String *result=new String();
return *result;
}
Here is what happens. You allocate a new String on the heap and store its pointer in
result
. So far so good. On return the
value of this object is put on the stack and returned the caller, i.e. it is copied because you are returning a String value and not a String*. Your pointer to the object on the heap is lost forever and hence you have created a memory leak. That's why this is no good idea.
There is a second reason: Allocating an object on the heap is much more expensive in terms of time than an allocation on the stack, because it requires thread synchronization in multi-threaded applications. So avoid that in low-level functions whenever possible.