Converting implicitly with converting constructor
Let's make the example in the question more complex
class MyClass
{
public:
int a, b;
MyClass( int i ) {}
MyClass( const char* n, int k = 0 ) {}
MyClass( MyClass& obj ) {}
}
First two constructors are converting constructors. The third one is a copy constructor, and as such it is another converting constructor.
A converting constructor enables implicit conversion from argument type to the constructor type. Here, the first constructor enables conversion from an int
to an object of class MyClass
. Second constructor enables conversion from an string to an object of class MyClass
. And third... from an object of class MyClass
to an object of class MyClass
!
To be a converting constructor, constructor must have single argument (in the second one, second argument has one default value) and be declared without keyword explicit
.
Then, initialization in main can look like this:
int main()
{
MyClass M = 1 ;
// which is an alternative to
MyClass M = MyClass(1) ;
MyClass M = "super" ;
// which is an alternative to
MyClass M = MyClass("super", 0) ;
// or
MyClass M = MyClass("super") ;
}
Explicit keyword and constructors
Now, what if we had used the explicit
keyword ?
class MyClass
{
public:
int a, b;
explicit MyClass( int i ) {}
}
Then, compiler would not accept
int main()
{
MyClass M = 1 ;
}
since this is implicit conversion. Instead, have to write
int main()
{
MyClass M(1) ;
MyClass M = MyClass(1) ;
MyClass* M = new MyClass(1) ;
MyClass M = (MyClass)1;
MyClass M = static_cast<MyClass>(1);
}
explicit
keyword is always to be used to prevent implicit conversion for a constructor and it applies to constructor in a class declaration.
X&
,const X&
,volatile X&
, orconst volatile X&
. – Wellintentioned