Explicit keyword in C++

Posted on June 23, 2012 by Mauricio Ferreira


« Previous | Home



When a class has just a single parameter constructor, the compiler is allowed to make a implicit conversion to resolve the parameters to a function. It is used to covert from one type to another in order to get the right type for a parameter.

For example, if we have the class Foo that has a single parameter constructor that receives and saves an int foo:


1
2
3
4
5
6
7
8
class Foo
{
public:
  Foo (int foo) {m_foo = foo;}
  GetFoo () {return m_foo;}
private:
  int m_foo;
};

And here is a function that takes and prints a Foo object:


1
2
3
4
5
void DoBar (Foo foo)
{
  int f = foo.GetFoo();
  cout << "DoBar: " << f << endl;
}

So, if DooBar is called like:


1
2
3
DoBar (12);
DoBar (22.6f);
DoBar ('A');

In each call of “DoBar”, the parameter is not a Foo object. In the first call is an int, the second is a float and the third call is a char. Though, there exists a constructor for Foo that takes an int so that constructor can be used to convert the parameter to the correct type. This example compiles and prints the following result:


1
2
3
DoBar: 12
DoBar: 22
DoBar: 65

Prefixing the explicit keyword 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 call DoBar.