The + operator should not be a member function, but a free function, so that conversions can be performed on either of its operands. The easiest way to do this is to write operator += as a member and then use it to implement the free function for operator +. Something like:
String operator +( const String & s1, const String & s2 ) {
String result( s1 );
return result += s2;
}
As others have suggested, you can overload for const char * for possible efficiency reasons, but the single function above is all you actually need.
Please note that your code as it stands should give an error for:
String s1("hi");
String s2("hello");
str2 = str1 + "ok"; // not OK!!!
something like:
warning: deprecated conversion from string constant to 'char*'
as the string literal (constant) "ok" is a const char *
, not a char *
. If your compiler does not give this warning, you should seriously think about upgrading it.