Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading

Why is overloaded operator= mandated to be a member function ($13.5.3), but not a compound assignment operator e.g. operator+= ($13.5.2)? Am I overlooking something here?

like image 773
Chubsdad Avatar asked Nov 16 '10 09:11

Chubsdad


3 Answers

A copy assignment operator=, as a member, is always provided by the compiler if the user doesn't define one. I believe that it was only for simplicity and to avoid unexpected ambiguities that it was made a requirement that operator= can't be defined as a free function.

Conversion operators take care of the case when you want to assign from a user-defined type to a built-in type.

like image 81
CB Bailey Avatar answered Sep 21 '22 18:09

CB Bailey


The sections you reference have this to say about hiding base class implementations of operator=

Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user (12.8),

This may also be the answer to your question, since the compiler needs to know if it should generate an operator= it must know if such an operator was defined, if it could be defined outside the class the compiler couldn't know if it was defined in a different translation unit.

e.g.

//a.h
class A { }; // compiler thinks A::operator= should be implicitly defined

//b.h
#include "a.h"
A& operator=(A& This, const A& other) { /*...*/ } // Oops it's explicitly defined

Compound operators, on the other hand, are not implicitly defined therefore there is no reason to force them to be declared as member functions.

like image 30
Motti Avatar answered Sep 21 '22 18:09

Motti


Along with default and copy constructors, operator= is also treated specially in C++. That means, even if you don't declare one, the compiler will provide a default implementation for you. But default implementations are not always the behaviour that suits your class' needs, that's why you should declare them explicitly (or hide them, by assigning private visibility).

And why is default constructor, copy constructor and assignment operator so special? Because they are involved in standard variable initialization and parameter passing: when you pass a class-typed parameter to a function by value (not by reference or pointer), these operations are called to copy it's content to the stack.

like image 23
buc Avatar answered Sep 25 '22 18:09

buc