Hello everyone,
I am reading the C++ Programming Language book, but can not find the function of explicit keyword of constructor. Could anyone explain its usage or refer some learning materials please?
thanks in advance,
George
Hello everyone,
I am reading the C++ Programming Language book, but can not find the function of explicit keyword of constructor. Could anyone explain its usage or refer some learning materials please?
thanks in advance,
George
A simple example is:
If we add the explicit qualifier to the the constructor for X, the "X b = 2;" statement will result in a compile time error. The idea is that using this syntax (constructor used for implicit conversions) can be misleading under some circumstances and so should not be allowed at those times.Code:class X { public: X(int x) : x_(x) {} private: int x_; }; int main() { X a(1); X b = 2; }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
explicit means you must pass the proper parameter types to your explicit constructor (i.e. the types can't be automatically converted to the proper type for you).
Perhaps a better example might be this:Code:class X { public: explicit X(int x) : x_(x) {} private: int x_; }; void foo(X x); int main() { X x1(3); foo(x1); // ok foo(X(3)); // ok foo(3); // not ok because of explicit }
If there is a class A and a class B:
And a function F:Code:class A { }; class B { B(const A &obj); };
Then you are allowed to call F with an object of type A, since it can be converted to an object of type B by the B(const A &) constructor. If you do NOT want this to be allowed, you must qualify the B(const A &) constructor with the "explicit" keyword.Code:void F(B obj) { }