Skip to main content

  | मौसम…

411 समाचार
Public archive edition · Attributed source reporting with original dates · AI drafts are excluded

411 REFERENCE · Wikibooks

C++ Programming/Programming Languages/C++/Code/Keywords/explicit

Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.

The explicit keyword is used to avoid implicit type conversions. Here's an exampleWhat does the explicit keyword mean?, 2008 class with a constructor that can be used for implicit conversions: class Foo { public: // single parameter constructor, can be used as an implicit conversion Foo (int foo) : m_foo (foo) { } int GetFoo () { return m_foo; } private: int m_foo; }; Here's a simple function that takes a Foo object: void DoBar (Foo foo) { int i = foo.GetFoo (); } and here's where the DoBar function is called. int main () { DoBar (42); } The argument is not a Foo object, but an int. However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type. The compiler is allowed to do this once for each parameter. Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar(42). It is now necessary to call for conversion explicitly with DoBar(Foo(42)) References C++ Programming