What does the explicit keyword mean?

Explanation

The explicit keyword means that there will be one explicit function which will be use in to control the unwanted implicit type conversions. This means it will not allow any specifier in the program for implicit conversions. And for this constructors are also used in the program. 

Here we will take an example class with a constructor that can be used for implicit conversions:

class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }

  int GetFoo () { return m_foo; }

private:
  int m_foo;
};

Here we will take a simple function that takes a Foo object:
void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}

And here we will call the function name as DoBar 

int main ()
{
  DoBar (42);
}

So here the argument is not a Foo object, but instead it is an int. However, there is a constructor for Foo that will  take an int . So that this constructor can be use in to convert the parameter to the correct type. And the compiler will also be allow to do this once for each parameter in the program.

So here if you use the explicit keyword before the constructor it will prevents the compiler from using that constructor for implicit conversions. After adding it to the above class will create a compiler error at the function call DoBar . So now it is now necessary to call for conversion explicitly with DoBar

 

Also read, Make an existing Git branch track a remote branch?

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *