0

Is the following definition OK with regards to the use of the ternary assignment operator in the constructor?

#include <cmath>
using namespace std;    

class Foo{
    private:
        complex z; // some complex number
        double arg; // the principal argument of z
    public:
        Foo(complex y) :
            z(y),
            arg(y.real() == 0.0 and y.imag() == 0.0 ? 0.0 : atan2(y.imag(), y.real())
        {}
};
user1892304
  • 617
  • 1
  • 6
  • 11
  • 1
    Wait, `y.real() == 0.0` and `y.imag() == 0.0` might cause problems. [You never should use direct equality comparisons with floating point values](https://stackoverflow.com/questions/588004/is-floating-point-math-broken/588029). – πάντα ῥεῖ Apr 06 '19 at 21:41
  • @πάνταῥεῖ No it compiles and runs but it feels "wrong" because I'm executing code in a place that shouldn't have any code, am I wrong? Also you never know with constructors/destructors, some things feel like they should work but lead to undefined behaviour (e.g. calling a polymorphic method in a constructor body, or throwing an exception in a destructor...) – user1892304 Apr 06 '19 at 21:41
  • 3
    _"because I'm executing code in a place that shouldn't have any code, am I wrong?"_ Regarding this concern you're wrong. It's perfectly fine, I don't get why you think it's illegal to execute any code there. – πάντα ῥεῖ Apr 06 '19 at 21:43
  • @πάνταῥεῖ Ok thanks! Good to be certain. Regarding floating point == : yes I'm aware that it is meaningless, but for the sake of the example I didn't want to go to the hassle of comparing the values to an `epsilon` constant etc. – user1892304 Apr 06 '19 at 21:45

0 Answers0