When constructor is explicit, it isn’t used for implicit conversions. In the given snippet, constructor is marked as explicit. Then why in case foo obj1(10.25); it is working and in foo obj2=10.25; it isn’t working ?
#include <iostream>
class foo
{
int x;
public:
explicit foo( int x ):x(x)
{}
};
int main()
{
foo obj(10.25); // Not an error. Why ?
foo obj2 = 10.25; // Error
getchar();
return 0;
}
error: error C2440: ‘initializing’ : cannot convert from ‘double’ to ‘foo’
There is a difference between these two lines of code. The first line,
explicitly calls your
fooconstructor passing in10.25. This syntax, in general, is a constructor call.The second line,
tries to implicitly convert from
10.25to an object of typefoo, which would require use of an implicit conversion constructor. In this example, you’ve marked the constructorexplicit, there’s no implicit conversion constructor available, and so the compiler generates an error.