c++ - What does the explicit keyword mean? -
someone posted in comment question meaning of explicit
keyword in c++. so, mean?
the compiler allowed make 1 implicit conversion resolve parameters function. means compiler can use constructors callable single parameter convert 1 type in order right type parameter.
here's example class constructor can used implicit conversions:
class foo { public: // single parameter constructor, can used implicit conversion foo (int foo) : m_foo (foo) { } int getfoo () { return m_foo; } private: int m_foo; };
here's simple function takes foo
object:
void dobar (foo foo) { int = foo.getfoo (); }
and here's dobar
function called.
int main () { dobar (42); }
the argument not foo
object, int
. however, there exists constructor foo
takes int
constructor can used convert parameter correct type.
the compiler allowed once each parameter.
prefixing explicit
keyword constructor prevents compiler using constructor implicit conversions. adding above class create compiler error @ function call dobar (42)
. necessary call conversion explicitly dobar (foo (42))
the reason might want avoid accidental construction can hide bugs. contrived example:
- you have
mystring(int size)
class constructor constructs string of given size. have functionprint(const mystring&)
, , callprint(3)
(when actually intended callprint("3")
). expect print "3", prints empty string of length 3 instead.
Comments
Post a Comment