Understanding the explicit keyword in C++
Loads the correct constructor type.
Specifies that a constructor or cast function (since C++ 11) is explicit, that is, it cannot be used for implicit casts and copy initialization.
Let’s take an example, you have the following code:
do_somethingfunction takes a parameter of type
TerminalRoot, but the compiler automatically converts it to
And you don’t want that, you want the correct type to be passed, because you want to know if there is a bug in that type. So you use the
explicit keyword, but when compiling there is an error compiling:
And then you get the error:
TerminalRoot. So you need to pass the correct type now:
do_something( TerminalRoot( 963 ) );
The output is
int ), but you have passed the correct type and verified that it is working . For more information see the link: https://en.cppreference.com/w/cpp/language/explicit .
That’s all for today, small daily doses that will always keep us in tune with C++!