C++ type conversion operator

You forgot the const on the double conversion operator:

operator double() const {  // <---------------------------
        cout << "operator double() called" << endl;
        return this->c;
    }
};

As in your example a is not const, the double conversion is the best match. If you fix that you get the expected output.

Live example

...some opinion based PS:

I didnt find what the core guidelines say about conversion operators, but if I had to make up a guideline for conversion operators it would be: Avoid them. If you use them, make them explicit. The surprising effects of implicit conversion outweigh the benefits by far.

Just as an example, consider std::bitset. Instead of offering conversion operators it has to_string, to_ulong and to_ullong. It is better to have your code explicit. A a; double d = a; is a little bit mysterious. I would have to look at the class definition to get an idea of what is really going on. On the other hand A a; double d = a.as_double(); can do the exact same thing, but is way more expressive.

Tags:

C++

Types

Casting