I think I'll just make the new object at the beginning instead of at the end and then update it's variables.
You could do that, but an alternative is to implement an member function operator+=, then implement a free function operator+ in terms of it. An untested example:
Code:
String& String::operator+=(const String& rhs) {
int templength = length + rhs.length;
char* tempbuf = new char[templength + 1]; // Account for null terminator.
tempbuf[0] = '\0';
strncat(tempbuf, buf, length);
strncat(tempbuf, rhs.buf, rhs.length);
delete[] buf;
length = templength;
buf = tempbuf;
return *this;
}
Now you can just write:
Code:
String operator+(const String& lhs, const String& rhs) {
return String(lhs) += rhs;
}
Note that operator+ no longer needs to be a friend function.