c++classoperator-overloadingoverloadingconversion-operator

What does operator float*() do?


I have been looking through source code trying to learn more about C++ and I came across some code that looked confusing. I haven't been able to figure out its use by playing around with it.

Please can someone explain what the operator float *() does and how it is used?

class Vector
{
public:
    float x,y,z;

Vector() : x(0), y(0), z(0){ } Vector( float x, float y, float z ) : x(x), y(y), z(z){ } operator float*(){ return &x; } operator const float *(){ return &x; }

I have searched StackOverflow and it looks like it is a conversion operator but I am still unsure what it actually does and why it is useful.

Kind regards,


Solution

  • operator type_name declares an implicit conversion operator. In other words, this function is called when you are attempting to (implicitly) convert an object of your type to float* – for instance in an assignment:

    Vector x(1, 2, 3);
    float* f = x;
    assert(*f == 1);
    

    Needless to say, this particular conversion is quite terrible because its effect is pretty unintuitive and easily results in impossible to find bugs. Implicit conversions should generally be handled with care since they hide potentially confusing semantics. But they can be used well with types which are supposed to be used interchangeably, and where a conversion doesn’t hurt.

    For instance, consider the case where you write your own integer and complex classes. A conversion from integer to complex is harmless, since every integer is a complex number (but not vice-versa). So having an implicit conversion integercomplex is safe.