Re: const MyClass& operator= ... ...
On Jul 9, 7:21 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
Victor Bazarov wrote:
nembo kid wrote:
Was wondering why the function that overloads = operator,
returns always a const reference to the class.
Why the qualifier 'const'?
First of all, the premise is untrue. The compiler-provided
operator= does not return the reference to a const object.
It returns a reference to a non-const object.
Second, if one of _your_ classes returns a reference to
const, they you need to ask yourself (or whoever gave you
the class) why the normal (idiomatic) interface was not
followed.
In fact, the operator=() can return *anything* (including
void). However, if you return anything else than a reference
to self, your class cannot be used in the traditional way with
assignments (except with a simple "a = b;").
That's not quite true. A const reference return type will
support all of the traditionan C uses of assignment. (In C,
assignment was not an lvalue.) Where it breaks are things like:
T&
someFunction( /* ... */ )
{
// ...
return a = b ;
}
Arguably, such idioms aren't good programming practice, and
should be avoided anyway. But they work with built-in types and
with the compiler generated default operator, and it seems best
that user defined operators adher as close as possible to the
way the built-in operators work.
One notable exception to this is proxy objects, where the
operator= itself is usually const.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34