In the book C++ Primer it has a code for C - style character arrays, and shows how to overload the =
operator in the Article 15.3 Operator =.
String& String::operator=( const char *sobj )
{
// sobj is the null pointer,
if ( ! sobj ) {
_size = 0;
delete[] _string;
_string = 0;
}
else {
_size = strlen( sobj );
delete[] _string;
_string = new char[ _size + 1 ];
strcpy( _string, sobj );
}
return *this;
}
Now i would like to know why is there the need to return a reference String &
when this code below does the same job, without any problem:
void String::operator=( const char *sobj )
{
// sobj is the null pointer,
if ( ! sobj ) {
_size = 0;
delete[] _string;
_string = 0;
}
else {
_size = strlen( sobj );
delete[] _string;
_string = new char[ _size + 1 ];
strcpy( _string, sobj );
}
}
It supports the following idiom:
String a, b;
const char *c;
// set c to something interesting
a = b = c;
For this to work, b = c
must return an appropriate object or reference to assign to a
; it's actually a = (b = c)
according to the C++ operator precedence rules.
If you'd return the pointer this
, you'd have to write a = *(b = c)
, which doesn't convey the intended meaning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With