What does the explicit keyword mean in C++?
What does the explicit keyword mean in C++?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The compiler is allowed to make one implicit conversion to resolve the parameters to a function. This means that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.
Here’s an example with converting constructors that shows how it works:
Prefixing the
explicitkeyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function callbar(42). It is now necessary to call for conversion explicitly withbar(Foo(42))The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:
MyStringclass with a constructor that constructs a string of the given size. You have a functionprint(const MyString&)(as well as an overloadprint (char *string)), and you callprint(3)(when you actually intended to callprint("3")). You expect it to print "3", but it prints an empty string of length 3 instead.