Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit on N-ary constructors?

In this presentation: http://qtconference.kdab.com/sites/default/files/slides/mutz-dd-speed-up-your-qt-5-programs-using-c++11.pdf

The author suggests that N-ary constructors benefit from the C++11 version of explicit keyword.

What changed in C++11 that makes this keyword useful if you have more than one constructor parameter?

like image 655
Klaim Avatar asked Dec 14 '12 21:12

Klaim


1 Answers

In C++11, if you have a non-explicit constructor for a class A that has multiple parameters (here I use A::A(std::string, int, std::string) as an example), you can initialize an argument of that type with brace initialization:

void foo(A a);
foo({"the", 3, "parameters"});

Similarly, you can do the same with return values:

A bar() {
  return {"the", 3, "parameters"};
}

If the constructor is, however, explicit, these will not compile. Hence, the explicit keyword now has importance for all constructors, rather than just conversion constructors.

like image 177
Joseph Mansfield Avatar answered Sep 19 '22 20:09

Joseph Mansfield