Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. So it is a good practice to add explicit keywords with constructors. Let see example codes to understand this concept.
#include<iostream>
using namespace std;
class Demo
{
private:
int data;
public:
Demo(int i):data(i)
{
}
void Display()
{
cout<<" data = "<<data<<endl;
}
};
int main()
{
Demo obj(6);
obj.Display();
obj = 27; // implicit conversion occurs here.
obj.Display();
return 0;
}
In the above-mentioned code, you can see how the constructor is working as a conversion constructor when assigning 27 to the object. When you will compile this code then it would be compiled and display the value of data.
I think you want to avoid this accidental construction because it can hide a bug. So using the explicit keyword we can avoid it. Because we know that prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Let see a code to understand this concept.
#include<iostream>
using namespace std;
class Demo
{
private:
int data;
public:
explicit Demo(int i):data(i)
{
}
void Display()
{
cout<<" data = "<<data<<endl;
}
};
int main()
{
Demo obj(6);
obj.Display();
obj = 27; // implicit conversion occurs here.
obj.Display();
return 0;
}
Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. So it is a good practice to add explicit keywords with constructors. Let see example codes to understand this concept.
In the above-mentioned code, you can see how the constructor is working as a conversion constructor when assigning 27 to the object. When you will compile this code then it would be compiled and display the value of data.
I think you want to avoid this accidental construction because it can hide a bug. So using the explicit keyword we can avoid it. Because we know that prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Let see a code to understand this concept.
Output:

need an explanation for this answer? contact us directly to get an explanation for this answer