What does the explicit keyword mean in C++?

C++Server Side ProgrammingProgramming

The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo −

class Foo {
    Foo(int n); // allocates n bytes to the Foo object
    Foo(const char *p); // initialize object with char *p

Now if you try

Foo mystring = 'x';

The char 'x' is implicitly converted to int and then will call the Foo(int) constructor. But this is not what was intended. So to prevent such conditions and make the code less error-prone, define the constructor as explicit −


class Foo {
      explicit Foo (int n); //allocate n bytes
      Foo(const char *p); // initialize with string p
Published on 28-Feb-2018 15:26:28