0

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:

  1. a conversion function (user-defined cast) accepting an Widget and returning a double
  2. The display_widget function having a double 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         |
+----------------------+------------------------------+   
Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42
  • did you try running your code? Did that answer your question? – Alan Birtles Sep 29 '19 at 16:12
  • @AlanBirtles Suppose I executed the code, and observed some result. That does not mean that the observed behavior is the general behavior. Perhaps which function is called is determined is some very arbitrary fashion. For example, which `display_widget` definition is closer to the top of the file might be the one which gets called. Even if the behavior is the same in general, it might be the same only for that one particular compiler. I don't know if the C++ standards specify what's supposed to happen in these situations. – Toothpick Anemone Sep 30 '19 at 00:58

0 Answers0