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.