-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.

6
  • 1
    An explicit constructor prevents that constructor on being used for implicit type conversions. Commented Apr 3, 2018 at 8:00
  • 1
    What precisely is it you are asking about? Especially after reading some documentation like en.cppreference.com/w/cpp/language/explicit Commented Apr 3, 2018 at 8:01
  • Actually move and copy constructors are typically supposed to be implicit. Commented Apr 3, 2018 at 8:01
  • @JesperJuhl Can you please provide an example on it? Commented Apr 3, 2018 at 8:02
  • 1
    I can't see a good use-case for an explicit copy constructor (including move constructor). Typically, it's converting constructors (i.e. ones that accept an argument of different type) where the implicit/explicit distinction is important. Commented Apr 3, 2018 at 10:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

In retrospect, that implicit conversation would better be asked for explicitly with an "implicit" keyword.
So does that mean that the keyword "explicit" is used only for single argument constructors?
@Kadiam Yes, if a constructor has more than one arguments (without default values) then it can't be used as a conversion constructor.
@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 All correct. :)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.