This is very trivial, but Czech language (my native) doesn't distinguish between implicit and default, so I am confused by some Czech translations what is the difference between implicit and default constructor or constructor call.
struct Test {
Test(int n=0) { }
};
Can you describe in these terms what the following statements do?
Test t1;
Test t2();
Test t3 = 3;
Test t4(4);
Test t5 = Test(5);
Best Answer
The terms default and implicit, when talking about a constructor have the following meaning:
default constructor is a constructor that can be called with no arguments. It either takes no arguments or has default values for each of the arguments taken.
implicit constructor is a term commonly used to talk about two different concepts in the language, the
implicitly declared constructor which is a default or copy constructor that will be declared for all user classes if no user defined constructor is provided (default) or no copy constructor is provided (copy). That is, a class with no constructors declared by the user has one default constructor implicitly declared.
implicitly defined constructor is a implicitly declared constructor that is used (odr-used1 in the language and for which the compiler will provide a definition.
In simple terms, a constructor is default if it can be called with no arguments. A constructor is implicit(ly declared/defined) if it is not provided by the user but declared/defined.
As of the specific cases:
Uses the default constructor,
Test(int = 0)
, which is not implicit.This is a strange quirk of the language, it declares a function that takes no arguments and returns a
Test
object.This is called copy-initialization and is equivalent to the composition of an implicit* conversion from
3
toTest
and copy construction oft3
from the result of the conversion. This will use theTest(int)
constructor for the conversion, and then the implicitly defined (and declared) copy constructor. Note: the compiler can optimize away the copy, but it must verify that the copy constructor is available (access specifiers) and can be defined.Uses the
Test(int)
constructor, which in this case is not acting as a default constructor.Equivalent to the
Test t3 = 3
case, with the only difference that the conversion from5
toTest
is explicit in this case. In this example it won't matter, but if the constructor had been marked asexplicit
this line would compile while thet3
case would fail.*) Yet another use of implicit, in this case referring to the fact that the conversion from
3
toTest
is not explicitly requested in the code. Compare this witht5
where the conversion is explicitly requested by the programmer:Test(5)
.