What does the explicit keyword mean in C++?


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 {
public:
    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 −

Example 

class Foo {
   public:
      explicit Foo (int n); //allocate n bytes
      Foo(const char *p); // initialize with string p
};

Updated on: 24-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements