First, let's clear up a few things:
+-------------+----------------+-----------------------+
| Expression | Type | Type as operator arg |
+-------------+----------------+-----------------------+
| toString() | std::string | std::string |
| "( " | char const[3] | char const* |
| '"' | char | char |
+-------------+----------------+-----------------------+
These are not all "strings".
The main issue here is that "( " + '"' does not do what you think it does. "Adding" a char to a const char* does not build a larger string; it adds a number to the string literal's pointer value. In doing this, you make a new pointer that points to… well… nowhere useful. In fact you're invoking undefined behaviour by incrementing the pointer so far.
It's a bit like this:
char const* whatYouAreDoing()
{
char const* a = "( ";
char b = '"';
int c = b;
assert(c == 34); // assuming ASCII
a += c; // whoops!
return a; // this pointer is now nonsense
}
Generally, if you want to "build" a string, you can use stream formatting:
virtual string write() const
{
std::stringstream ss;
ss << "( " << '"' << toString() << '"' << " )";
return ss.str();
}
Or, in this case, since you actually don't need all those literals, the following will be fine:
virtual string write() const
{
return "( \"" + toString() + "\" )";
}
toString()should beconst. Not sure why you suggested making it non-const, especially as that has nothing to do with the problem at hand.