1
MyClass& operator=(const MyClass& other)
{
   //Implement
   return *this;
}
MyClass operator=(const MyClass& other)
{
   //Implement
   return *this;
}
void operator=(const MyClass& other)
{
    //Implement
}

When I test these methods, the result is the same. In almost book I see that the first method(MyClass&) is used more than the second method. what's different between them? Which method is really right and fast? One method return address and the second return value.

bm2i
  • 75
  • 1
  • 1
  • 7

1 Answers1

2

When I test these methods, the result is the same.

it depends on how you test your class, ie.:

void foo (MyClass& a);

MyClass a1;
MyClass a2;

foo(a1 = a2);

in case of second operator implementation (returning MyClass), above code (inside foo) will not modify a1 instance, but a temporary value.

In almost book I see that the first method(MyClass&) is used more than the second method.

and thats correct, its more correct to return reference to *this in assignment operator

what's different between them? Which method is really right and fast?

first version is faster and correct because it does not do any copy of your object, also its more proper because thats how primitive types behave, ie:

int n = 0;
int k = 10;
(n = k) = 1;
std::cout << n;

here on output you will get 1, because (n = k) returns reference to n.

marcinj
  • 48,511
  • 9
  • 79
  • 100