String & String::operator=(const String & st)
{
if (this == &st)
return st;
delete [] str;
len = st.len;
return st;
}
Multiple errors here:
1. the statements
return st
try to return a const reference when a non-const reference was required.
2. Not only that, you are also returning the wrong object. The general consensus is that the method
operator=()
always returns a reference to the object that is being assigned to. Just use
return *this;
instead.
3. you delete
str
, but do not assign it again. You should copy
st.str
here.
Moreover ...
String::String(const char * s)
{
len = strlen(s);
str = new char[len];
str = static_cast<char*>(s);
}
Again, multiple errors here:
1. You did not check whether s is a Null pointer. your call to
strlen
will crash if it is.
2. the third line will overwrite the pointer to the newly allocated memory from line 2, the memory will thus be lost - you created a memory leak.
3.
static_cast
is the wrong type of cast here; if your goal is to cast away
const
, then use
const_cast
4. That said, you shouldn't use
const_cast
either - for one, using a cast is usally just an indication that you're doing something wrong. Most of the time, all it does is suppress compiler errors or warnings, not fix the erroneous code. Second, you should not copy the pointer here, but copy the contents of
s
to the newly created string, e. g. with
strcpy()
One more thing: do not write
num_strings
with the standard serialization operators - it is a static variable, and as such a property of the class, not a property of the instances of this class. If you want to write that value, do it outside the class.
As an aside, not all of your constructors increment
num_strings
, so this value will likely not be correct.