C++/C++ Implicit Conversion...
Expert: Zlatko - 2/2/2010
QuestionHi,
What is the problem with implicit conversion constructor?.. Why we need explicit conversion with the keyword Explicit?.. could please elaborate?
AnswerImplicit conversion occurs with single parameter constructors. It is easy to accidentally have the conversion constructor called. If the conversion is expensive in time or memory, it should probably be avoided. Instead, a function to work with the original data-type should be created.
For example:
class A
{
public:
A(int a) { /* expensive constructor */ }
};
int function(A a)
{
return 0;
}
int main(void)
{
while(true)
{
function(1);
}
return 0;
}
Here main calls function with an integer but the writer did not know that function only takes an A object and that an A object will be created each time through the loop. By making A::A(int) explicit, the compiler will say that function cannot be called with an integer. The writer should then provide a function that takes an integer.
Honestly, I never used the explicit keyword, but I think it is a good habit to make single variable constructors explicit when possible and then remove the restriction only when necessary - much like many programmers do with the const keyword.
Thanks for the question.