Does specifying a method/constructor explicit mean that it can't be called implicitly? I mean if a constructor is specified as explicit, can't it be called implicitly by some operator like = or other methods like converter constructor?
In that case, does specifying a method/constructor to be explicit have any importance at all?What are the advantages of specifying a method/constructor to be explicit?
class MyClass
{
int i;
MyClass(YourClass &);
};
class YourClass
{
int y;
};
void doSomething(MyClass ref)
{
//Do something interesting over here
}
int main()
{
MyClass obj;
YourClass obj2;
doSomething(obj2);
}
In the example since constructor of MyClass
is not specified as explicit, it is used for implicit conversion while calling the function doSomething()
. If constructor of MyClass
is marked as explicit then the compiler will give an error instead of the implicit converstion while calling doSomething()
function. So if you want to avoid such implicit conversions then you should use the explicit
keyword.
To add to the above: keyword explicit
can be used only for constructors and not functions. Though it can be used for constructors with more than more parameters, there is no practical use of the key word for constructors with more than one parameter, since compiler can only use a constructor with one parameter for implicit conversions.