In a GoogleTechTalks video on Youtube, Bjarne Stroustrup talks about the upcoming C++0x standard. In the video he mentions the following example:
#include <iostream>
struct Sick
{
Sick(double d) { std::cout << d << "\n"; }
explicit Sick(int i) { std::cout << i << "\n"; }
};
int main()
{
Sick s1 = 2.1;
Sick s2(2.1);
}
Did he mean to place the explicit keyword before Sick(double) rather than Sick(int), in order to highlight problems associated with implicit conversions in certain contexts?
In his discussion, Stroustrup mentions that a direct initialization, such as
will consider only constructors marked
explicitif there are anyexplicitconstructors. That’s not my experience with several compilers (including GCC 4.6.1 and MSVC 16/VS 2010), and I can’t find such a requirement in the standard (though I’d be interested if someone can point it out).However, if ints are used in the initializers, I think the example would show what Stroustrup meant to demonstrate:
Running the above will display:
Shows that the two apparently equivalent initializations actually select different constructors.
(Or as Truncheon mentioned in the question – and I missed – that the
explicitkeyword should be on theSick(double d)constructor).