Multi-argument constructors with default parameters & explicit keyword
Recently I was reviewing some snippet of code. It looked similar to following.
At a glance I spotted the explicit keyword and wondered if it's needed. It's obvious that for one-argument constructors it is needed, if we don't want compiler to perform implicit conversions. However, what is the behavior when there's more than one arguments, but with default values?
I dig into the C++ standard and found relevant example [N3242] § 12.3.1/1. In the example there's a constructor accepting const char* as the first argument and int as the second one. The second one has default value of 0.
So the rule is that any explicit multi-argument constructors may become implicit if they have all but one arguments with default values.
1 struct S {
2 explicit S(int someParam, int otherParam = 0) {
3 // Implementation...
4 }
5 };
At a glance I spotted the explicit keyword and wondered if it's needed. It's obvious that for one-argument constructors it is needed, if we don't want compiler to perform implicit conversions. However, what is the behavior when there's more than one arguments, but with default values?
I dig into the C++ standard and found relevant example [N3242] § 12.3.1/1. In the example there's a constructor accepting const char* as the first argument and int as the second one. The second one has default value of 0.
So the rule is that any explicit multi-argument constructors may become implicit if they have all but one arguments with default values.