[Development] operators as members or not

Olivier Goffart olivier at woboq.com
Thu Aug 15 09:40:44 CEST 2013


On Thursday 15 August 2013 03:11:20 Glen Mabey wrote:
> Hello,
> 
> I'm working on a couple of new classes and I wonder whether there is a
> policy (written or otherwise) on whether operators should be members or
> not.
> 
> In particular, this question has come up in
>   https://codereview.qt-project.org/#change,59605
> and
>   https://codereview.qt-project.org/#change,60792
> 
> I am no C++ philosopher, but I understand that some authorities (like
> stackoverflow) have their reasons for asserting that operators should not
> be members -- they also cite some sources.
> http://stackoverflow.com/questions/4421706/operator-overloading/4421729#442
> 1729
> 
> Looks like Oliver Goffart did also weigh in on the issue, in 60792.
> 
> Is it possible that the Coding Conventions could be amended to indicate
> which way this issue should go, if only for new classes?

The stack overflow answer says it well:

Binary operator that treat both their member equaly should not be member.
Because, in addition to the other reason mentioned in the stack overflow 
answer, the member are not equals when the operator is a member.

Example with QLineF which unforortunatelly has its operator== as a member:

 QLineF  lineF;  QLine lineN;

 if (lineF == lineN) //Ok,  lineN is implicitly converted to QLineF
 if (lineN == lineF) //Error: QLineF cannot be converted implicitly to QLine,
                           // and the LHS is a member so no conversion applies

If the operator== was outside of the class, conversion rules would applies 
equaly for both sides.


Some Qt classes have their operator as a member, but it is a mistake that we 
cannot fix without breaking binary compatibility. But new operator should be 
outside of the class.
 
-- 
Olivier

Woboq - Qt services and support - http://woboq.com - http://code.woboq.org




More information about the Development mailing list