What is the explicit keyword in C++?

Take a look at the code below

#include <iostream>
using namespace std;
class Blah
{
public:
// Overloaded constructor
Blah(int blah)
{
m_blah = blah;
}
int GetBlah()
{
return m_blah;
}
private:
int m_blah;
};
void Ext_Blah (Blah blah)
{
int x = blah.GetBlah ();
}
int main() {
// your code goes here
Ext_Blah (3);
}

Upon executing the code, it can be seen that the code compiles without any error; but, take another look at the definition of Ext_Blah(). Its input parameter is a Blah object, but we are passing an int to this function from main.

There exists a constructor for Blah that takes an int; so, this constructor can be used to convert the parameter to the correct type. The compiler is allowed to do this for each parameter once.

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. It will now ​create a compiler error at the Ext_Blah(3) function call.

See the code below:​

#include <iostream>
using namespace std;
class Blah
{
public:
// Overloaded constructor
explicit Blah(int blah)
{
m_blah = blah;
}
int GetBlah()
{
return m_blah;
}
private:
int m_blah;
};
void Ext_Blah (Blah blah)
{
int x = blah.GetBlah ();
}
int main() {
// your code goes here
Ext_Blah (3);
}

It is now necessary to call for a conversion explicitly with Ext_Blah(Blah (3)), ​​as shown below:

#include <iostream>
using namespace std;
class Blah
{
public:
// Overloaded constructor
explicit Blah(int blah)
{
m_blah = blah;
}
int GetBlah()
{
return m_blah;
}
private:
int m_blah;
};
void Ext_Blah (Blah blah)
{
int x = blah.GetBlah ();
}
int main() {
// your code goes here
Ext_Blah (Blah(3));
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved