Search code examples
c++explicitexplicit-constructor

Do we need explicit for CTOR with pointer type?


Do we need explicit in this case:

class A
{
    explicit A(B* b);
};

I think that even if we do not mark the constructor as explicit, it will be a compilation error to write:

A a = new B(); 

Implicit conversion from pointer to an object is not possible via a constructor at all, right?


Solution

  • It will fail to compile Conversion will fail from B* to A.

    This is exactly the kind of thing the explicit will prevent.

    You should just write A a( new B() ); in this case or if you want to be real verbose you could write A a = A( new B() );

    As to the root question: do you need it or not that's up to you and your team. Generally a main question is : are you ever going to have an 'int' constructor ( will lead to amibiguity with * types ), what do you want to happen, and do you want implicit conversions to happen from construction arguments or not.