Why the return on an assignment operator method?

Asked

Viewed 100 times

3

I’m learning about overload operators, but I don’t understand why the return at the end of the method. It would not be enough just to create new memory allocation?

StringBad & StringBad::operator=(const StringBad & st)

{

    cout<<"**********USANDO O OPERADOR************";

if (this == &st)    // object assigned to itself

return *this;   // all done

delete [] str;  // free old string

len = st.len;

str = new char [len + 1];   // get space for new string

std::strcpy(str, st.str);   // copy the string

return *this;   // return reference to invoking object

}

This is the main():

StringBad headline1("Celery Stalks at Midnight");
StringBad knot;

knot =(headline1);

cout << "knot: " << knot << endl;

cout << "Exiting the block.\n";

cout << "End of main()\n";

1 answer

1


No, because operators are expressions and expressions must always generate a result to be used where it is written, and a result is generated with a return.

If only he were statement would not need, but the language did not specify so. This is a statement:

knot = headline1;

This is an expression knot = headline1. Using in code can be perceived better:

cout << "knot: " << knot = headline1 << endl;

This way you’re attributing something to knot and using this as an argument in cout.

I put in the Github for future reference.

  • then the return is a rule in this case is mandatory

  • Yes, according to the language specification.

  • OK THANKS AGAIN !!! YOU ARE A BEAST THANK YOU EVEN

  • @dougllas you can already vote on everything on the site, see the [tour].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.