Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator= overloading in C++

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 );
   }

}
  • please help out.
like image 380
Sadique Avatar asked Mar 28 '11 18:03

Sadique


1 Answers

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.

like image 191
Fred Foo Avatar answered Oct 15 '22 18:10

Fred Foo