-1

I am newbie in C++ 11. I found this term of explicit constructor. However I did not find any good explanation on explicit constructor. Can you please explain in what scenario I should use explicit constructor?

Thank you in advance.

aliceangel
  • 304
  • 1
  • 5
  • 19

2 Answers2

5

A non-explicit one-argument constructor could be called a conversion constructor. That's because they allow the compiler to implicitly convert from another type (the type of the argument) to the object.

This implicit conversion is not always wanted, and can be disabled by marking the constructor explicit.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 2
    In retrospect, that implicit conversation would better be asked for explicitly with an "implicit" keyword. – curiousguy Jun 12 '18 at 22:27
  • So does that mean that the keyword "explicit" is used only for single argument constructors? – Kadiam Apr 19 '22 at 10:32
  • 1
    @Kadiam Yes, if a constructor has more than one arguments (without default values) then it can't be used as a conversion constructor. – Some programmer dude Apr 19 '22 at 10:40
  • @Someprogrammerdude your reply caused me to ask another question :) As you just mentioned, if a constructor with multiple arguments has default values for every argument except for one, then such constructor can be used as a conversion constructor. In that case, we can use the explicit keyword to prevent it happening. Am I right? – Kadiam Apr 22 '22 at 10:50
  • 1
    @Kadiam All correct. :) – Some programmer dude Apr 22 '22 at 10:54
2

An explicit constructor is a function that does not get called in implicit type conversion.

For example:

class A {
   A( int a ) {}
};

void foo( A a ) {}

Here is totally legal to call foo(1) or use any variable of type int or that can be implicitly converted to an int. This is not always desirable, as it would mean that A is convertible from an integer, instead of being defined with an integer. Adding the explicit would avoid the conversion and, hence, give you a compilation error.

Jorge Bellon
  • 2,901
  • 15
  • 25