Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

The explicit keyword: What is the purpose of using explicit in front of a constructor?

0
Posted

The explicit keyword: What is the purpose of using explicit in front of a constructor?

0

The keyword explicit is used to modify constructors. The problem: compilers always try to make type conversions instead of returning errors. A 1-parameter constructor is fair game for such implicit conversion. But often the client programmer would prefer to see an error, where it is not likely the programmers intent to convert and integer, say, to a vector. For example: void f (std::vector v); … int main() { int x; … f(x); // calls f incorrectly, using an int instead of a vector … } Note that the incorrect call would be allowed by the compiler if there is a 1-parameter constructor for vector that is not “explicit”. This could be a source of strange behavior if the implicit type conversion was not intended. The “explicit” modifier allows the use of the constructor only when it is actually called explicitly, not as an implicit type conversion mechanism.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123