I recently came across some weird looking class that had three constructors:
class Class { public: explicit Class(int ); Class(AnotherClass ); explicit Class(YetAnotherClass, AnotherClass ); // ... }
This doesn't really make sense to me - I thought the explicit keyword is to protect compiler chosen construction from a foreign type.
Is this allowed? If it it, what does it mean?
The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo − class Foo { public: Foo(int n); // allocates n bytes to the Foo object Foo(const char *p); // initialize object with char *p };
A copy constructor has one parameter that is a reference to the type that is copied. It can have additional parameters, if these have default values.
It is used to prevent a specific constructor from being called implicitly when constructing an object. For example, without the explicit keyword, the following code is valid C++: Array a = 10; This will call the Array single-argument constructor with the integer argument of 10.
In C++11 multi-parameter constructors can be implicitly converted to with brace initialization.
However, before C++11 explicit
only applied to single-argument constructors. For multiple-argument constructors, it was ignored and had no effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With