You are here:

C++/C++ Implicit Conversion...

Advertisement


Question
Hi,
What is the problem with implicit conversion constructor?.. Why we need explicit conversion with the keyword Explicit?.. could please elaborate?

Answer
Implicit 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.

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.