class MyClass {
public:
...
MyClass & operator=(const MyClass &rhs); // return MyClass&
...
}
why not
class MyClass {
public:
...
MyClass operator=(const MyClass &rhs); // return MyClass
...
}
Is it the reason that it is more efficient to return by reference in this case?
Thank you
// * updated *
I think I found the key reason as follows:
int i1, it2, i3;
(i1 = i2) = i3; // i3 will be assigned to i1
If the return type of operator= is MyClass rather than MyClass&, then the following statement doesn't perform the same as the internal data type.
MyClass mc1, mc2, mc3;
(mc1 = mc2) = mc3;
It is considered as a good practice by following the rules used by the built-in types.
// *** update ***
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i1, i2, i3;
i1 = 0;
i2 = 2;
i3 = 3;
(i1 = i2) = i3;
cout << "i1: " << i1 << endl;
cout << "i2: " << i2 << endl;
cout << "i3: " << i3 << endl;
return 0;
}
// output from VS2010
/*
i1: 3
i2: 2
i3: 3
*/