Is an explicit keyword necessary when a constructor takes multiple parameters?

This question refers to the previous C ++ 11 standard (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 prevent explicit ? I understand that in C ++ 11 you have a fixed initialization, so it will prevent constructs such as:

 struct Foo { explicit Foo(int, int); }; Foo f = {4, 2}; // error! 

But in C ++ 03, we don’t have fixed initialization, so what construct is explicit keyword prevention here?

+8
c ++ c ++ 03
source share
2 answers

If we have a constructor that takes two or more parameters, what will prevent explicit ?

Nothing.

+4
source share

It may be interesting if someone changes the signature of your method with the default parameter:

 struct Foo { explicit Foo(int, int = 0); }; 

With the explicit keyword, you idiomatically say that you never want the constructor to perform an implicit conversion.

+5
source share

All Articles