This question pertains to the preceding standard of C++11 (C++03). explicit
prevents implicit conversions from one type to another. For example:
struct Foo
{
explicit Foo(int);
};
Foo f = 5; // will not compile
Foo b = Foo(5); // works
If we have a constructor that takes two or more parameters, what will explicit
prevent? I understand that in C++11 you have braced initialization, so it will prevent constructions such as:
struct Foo
{
explicit Foo(int, int);
};
Foo f = {4, 2}; // error!
But in C++03 we don't have braced initialization, so what kind of construction is the explicit
keyword preventing here?
It might be interesting if someone change the signature of your method with a default parameter :
struct Foo
{
explicit Foo(int, int = 0);
};
With the explicit
keyword, you idiomatically say that you do not ever want a constructor to do implicit conversion.
If we have a constructor that takes two or more parameters, what will
explicit
prevent?
Nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With