0

If a class is written well, you should be able to gleam all relevant information about the class simply by looking at its header.

If one sees that the constructor is marked explicit:

  1. What should one assume to be absolutely true about this class?
  2. What should one assume to be potentially true about this class.
  3. What sort of bugs could one expect, if explicit is violated somehow?

If what I am asking is not clear; In the same way that if I see a member function marked virtual void sneed() = 0;

  1. Its absolutely true that this is an abstract class
  2. Its potentially true that this is some sort of factory
  3. And that if I do not impliment it, the program will not compile.

Thanks.

Anon
  • 3,639

1 Answers1

2

Some constructor are conversion constructors, i.e. it can be used to transform an object of a type provided as argument, into an object of that class. This can sometimes lead to nasty bugs, when the compiler tries to use such a conversion behind the scene in an unexpected way (example).

If the conversion constructor is marked explicit, the compiler will not use it for conversions without an explicit request, i.e.

only where the direct-initialization syntax or where casts are explicitly used

Note that the explicit keyword may also be used with conversion functions, to prevent the same kind of problems.

In conclusion, you cannot infer anything general about the class. explicit has no impact on the class but only restricts the way its constructor (or conversion functions) may be used.

Christophe
  • 81,699