preserving beyond a function
In the chap. of Prata that I'm currently working on, he creates a simplified version of the string class with the name String. It allocates memory dynamically for the char array, and he shows you how to build constructor, destructor, copy constructor, assignment operator and a few others.
Then as part of an exercise (No. 2, p. 629), you're supposed to add some things to the class he has delivered in the chapter. First, you're supposed to overload the + operator to concatenate two Strings, and that's where I'm having a scope issue.
This is my prototype, and I think that's really the way the prototype should look:
String & operator+(const String &) const;
Then I tried the following implementation, which I doubted would work (and it didn't) but which seemed the only way to do it. "len" is a private member variable giving the (int) length of the array, and "str" is the private member variable holding the relevant C-string.
This compiles but gives me a run-time error on a simple test program just as you leave the function, and I'm assuming it's because the joinSt variable gets destroyed as you leave the function.
String & String::operator+(const String & st) const
cout << "Entering operator+\n";
joinSt.len = len + st.len;
delete  joinSt.str;
joinSt.str = new char[joinSt.len + 1];
joinSt.str[len] = '\0';
cout << "Still in operator+\n";
My dilemma: For the return value to exist AFTER the function is called, it has to exist BEFORE the function is called, hence be input. But + takes 2 arguments, neither of which should be changed by calling it, and it returns one value that isn't an input (or at least I'm not seeing how to preserve the proper syntax for operator+ and put in some dummy String that becomes the result).
So, how do I keep my concatenated "String" alive outside of the operator+ function?