Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

explicit
keyword
c++

What is the explicit keyword in C++?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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));
}

RELATED TAGS

explicit
keyword
c++
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring