Categories
Linear Maths in C++

Polymorphic operators

Some time ago the C++ bool operator==(Class c) returned the wrong result for some comparisons. We couldn’t see why looking at the code and to hit the deadline, we made work-around and ignored it. This happens at work but it stayed with me, and many years later a CppCon video explained that as a class member, the argument is the same type or can be coerced to that type. If coercion fails, the function fails.

The safe solution is to put the operator== outside the class. The function then takes two args, and can be a friend if you need access to private data. So I put my Matrix operators as functions in the LinearMath namespace.

Modern C++ allows us to make the coercion explicit. Is this enough to protect against spurious calls ? That experience with a failing comparison operator was not replicated.

2 replies on “Polymorphic operators”

I’m extremely impressed together with your writing skills and also with the layout in your weblog. Is that this a paid topic or did you customize it yourself? Either way keep up the excellent high quality writing, it抯 rare to peer a nice blog like this one today..

Leave a Reply

Your email address will not be published. Required fields are marked *