supermalf avatar

Explicit keyword in C++

supermalf

Published: 22 Sept 2018 › Updated: 22 Sept 2018Explicit keyword in C++

Explicit keyword in C++

When a class has just a single parameter constructor, the compiler is allowed to make an implicit conversion to resolve the parameters to a function. It is used to convert 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:

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:

void DoBar (Foo foo)
{
  int f = foo.GetFoo();
  cout << "DoBar: " << f << endl;
}

So, if DooBar is called like:

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:

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.

Leave Explicit keyword in C++ to:

Written by

Read more #programming posts


Best Posts From supermalf

We have not curated any of supermalf's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From supermalf