Do we need explicit for CTOR with pointer type?

118 Views Asked by At

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?

3

There are 3 best solutions below

1
On BEST ANSWER

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.

3
On

Do we need explicit for CTOR with pointer type?

It depends on you and your team, if you are working in a team. It's more of a coding guideline than anything else. The language doesn't mandate it.

2
On

You do need the explicit if you do not want that constructor to be usable for implicit conversions. It is perfectly possible to have a constructor-based implicit conversion accepting a pointer.