-3

I have seen many post regarding explicit keyword but no where find the answer for why its failing. I have seen other post in stack overflow also but Regarding the conversion its very confusing kind of explanation given

class Foo {
public:
  explicit Foo(int x);
};
int main()
{
Foo a = 42;         //Compile-time error 
Foo b(42);          //OK: calls Foo::Foo(int) passing 42 as an argument
}

what exactly happening when we are writing Foo a = 42; , and how its differ from Foo b(42);

sss
  • 21
  • 3

2 Answers2

0
Foo a = 42;

if a constructor can be called with a single parameter, then it is a conversion constructor.Single argument can be converted to the class being constructed.

To disallow this you mark the constructor as explicit so such implicit conversions are not allowed, hence the error.

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
0

Foo a = 42; is copy initialisation.

And the C++ standard states that

explicit constructors are not converting constructors and are not considered for copy-initialization.

Reference: http://en.cppreference.com/w/cpp/language/copy_initialization

So it's a, perhaps lesser-known, effect of explicit.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483