Thursday, October 1, 2009

explicit keyword in C++

Look at the following code.

Here ABC a=100 is equivalent to ABC a(100);
This is known as an implicit conversion. This reduces the readability of the code. This can be avoided by using the keyword explicit.

By prefixing the constructor with the explicit keyword, we can prevent the compiler from using that constructor for implicit conversions.

Look at the following code.

In this case ABC a=100 will be an error. We can only call this by using the constructor notation.

Some more information about explicit...

  • The explicit keyword is used to declare a single-argument constructor that can only be called explicitly. If the constructor takes multiple argument, it's use is useless.

  • It is only used in declarations of constructors within a class declaration.

No comments:

Post a Comment