Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Function cannot have specifier explicit. It doesn't make sense for a fnc to have an explicit specifier. And as for ctor - the answer to your Q is Yes. Stating that ctor is explicit it means that it is illegal to call it implicitly.
When is it useful? In situation when for example your class:

class X
{
X(char){/*something really cool*/}
};

and later in code you would write:

X _1 = 'a';//this line will call conv ctor

With line like this above very often happen that programmer has had something different in mind and this conversion is totally unintentional.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top