Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading operator = return by value or reference?

1) What is the difference between:

complex& operator = (const complex& c);

and

complex operator = (complex c);

2) are they the same if I define (in the second case) a copy constructor?

complex::complex (const complex& c){

    //code
    }

3) what is the funcion of const?

like image 542
user2734408 Avatar asked Oct 17 '25 01:10

user2734408


1 Answers

Those are very different

Do you want chained assignments? Return *this.

a = b = c; // Chained assignment

Default assignment in C++ supports chaining, so it's a good idea to keep this rule.

To support this type of assignment each operation has to return a reference to *this or return a copy:

complex& operator = (const complex& c)
{
  // do assignment

   return *this;
}

or

complex operator = (const complex& c)
{
  // do assignment

   return *this;
}

But this simple job should be light and efficient. Assume no RVO or moving is available, then returning a reference rather than a copy is preferred.

 

Another reason that I prefer returning a reference is to get rid of a confusing thing in my mind. See these two scenarios:

// Returning a reference
a = 1;
b = 2;
c = 3;
(a = b) = c;

After assignments, a=3 b=2 c=3. Because, first b assigns to a and returns a reference to a, then c assigns to that reference and a changes again.

// Returning a copy
a = 1;
b = 2;
c = 3;
(a = b) = c;

After assignments, a=2 b=2 c=3. Because, first b assigns to a and returns a temporary copy, then c assigns to that temporary object (no effect on a or b).

As you can see, the results are different. Ignoring what happens and which one is better. You should choose a way which is popular and expected for programmers. I believe C++ programmers by watching (a = b) = c expect first result.

Therefore you should use first one.

 

About keyword const:

When you pass an object by reference to a function, the function can modify it. You can put a const to protect it against unwanted changes.

like image 193
masoud Avatar answered Oct 18 '25 14:10

masoud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!