"You should of course heed the warning and fix your code:\n",
"\n",
"* Make `operator double` explicit. Except in very specific cases, I advise you to always make such conversion operators explicit to avoid unintended side effects as the one we've just got.\n",
"* If commutativity is important for you, make `operator*` a friend function instead of a method and provide both ordering of arguments. \n",
"* If commutativity is important for you, make `operator*` a free function instead of a method and provide both ordering of arguments. \n",
"\n",
"The solution file implements both these modifications."
]
...
...
%% Cell type:markdown id: tags:
# [Getting started in C++](/) - [Operators](/notebooks/3-Operators/0-main.ipynb) - [TP 8 - Solution](/notebooks/3-Operators/1b-TP.ipynb)
%% Cell type:markdown id: tags:
<h1>Table of contents<spanclass="tocSkip"></span></h1>
What happens in fact is that `operator*` is not commutative: it expects as first argument an object and as second argument an integer.
So why does it work nonetheless?
`operator*(int, PowerOfTwoApprox)` is not defined... but addition between an integer and a double is obviously possible, AND you've just defined before an implicit conversion to `double`.
You should of course heed the warning and fix your code:
* Make `operator double` explicit. Except in very specific cases, I advise you to always make such conversion operators explicit to avoid unintended side effects as the one we've just got.
* If commutativity is important for you, make `operator*` a friend function instead of a method and provide both ordering of arguments.
* If commutativity is important for you, make `operator*` a free function instead of a method and provide both ordering of arguments.
The solution file implements both these modifications.
_This notebook is an adaptation of a lecture prepared and redacted by David Chamont (CNRS) under the terms of the licence [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](http://creativecommons.org/licenses/by-nc-sa/4.0/)_
_The present version has been redacted by Sébastien Gilles and Vincent Rouvreau (Inria)_