views:

75

answers:

3

This is a follow up to my previous question.

Consider that I write a function with the following prototype:

int a_function(Foo val);

Where foo is believed to be a type defined unsigned int. This is unfortunately not verifiable for lack of documentation.

So, someone comes along and uses a_function, but calls it with an unsigned int as an argument.

Here the story takes a turn. Foo turns out to actually be a class, which can take an unsigned int as a single argument of unsigned int in an explicit constructor.

Is it a standard and reliable behavior for the compiler to render the function call by doing a type conversion on the argument. I.e. is the compiler supposed to recognize the mismatch and insert the constructor? Or should I get a compile time error reporting the type mismatch.

+6  A: 

In case when Foo has a constructor for unsigned int implicit conversion will take place unless Foo is not declared explicit.

The first case:

class Foo { public: Foo(unsigned int) {} };
// ...
a_function( 1 ); // OK

Second case:

class Foo { public: explicit Foo(unsigned int) {} };
// ..
a_function( 1 ); // error

According to C++ Standard only one user-defined implicit conversion is allowed.

Kirill V. Lyadvinsky
A: 

Yes it is correct behavior of the compiler to do type conversion like that. If it didn't than things like conversion constructors or implicit conversion wouldn't be possible.

It's best to prevent things like that from happening through good practice and documentation which your function seems to be suffering from the lack of.

LoudNPossiblyRight
A: 

If the constructor is explicit then a_function(50U); would result in a compile error while a_function(Foo(50U)); would work.

This feature is in the language to prevent exactly this sort of accidental conversion.

Mark B