My question is if conversion functions (user-defined casts) take precedence over direct calls.
Suppose that you overload a function:
void display_widget( double f );
void display_widget( Widget a );
My question is, which has higher precedence:
- a conversion function (user-defined cast) accepting an
Widget
and returning adouble
- The
display_widget
function having adouble
in its parameter list
#include <iostream>
class Widget {
public:
Widget() : d{ 0.0 } {};
double get_d() { return d; }
operator double() {
std::cout << "operator double() was called" << std::endl;
return d;
}
private:
double d;
};
void display_widget( double widget ) {
std::cout << "The double is: " << widget << std::endl;
}
void display_widget( Widget widget ) {
std::cout << "The Widget is: " << widget.get_d() << std::endl;
}
int main(int argc, char* argv[]) {
Widget a{ 79.99 };
display_widget(a);
return 0;
}
Note that we have two display_widget
functions, one accepting an Widget
and the other accepting a double
Consider the following line inside of main
:
display_widget(a);
Which of the following sequence of print statements will we see?
+----------------------+------------------------------+
| option 1 | option 2 |
+----------------------+------------------------------+
| The Widget is: 79.99 | operator double() was called |
| | The double is: 79.99 |
+----------------------+------------------------------+