Explicit modifier for constructors taking reference argument

150 views Asked by At

I read that it's a good practice to define single argument constructors explicit in order to avoid implicit conversions. I understand the pitfall of having int value promoted to class object. I wonder if it also applies to the constructors accepting reference types. How one can provoke implicit conversion in this case:

class Foo
{
public:
    Foo(Bar& bar) { }
};

Does the situation changes if the constructor accepts pointers, is conversion from NULL and nullptr possible ?

class Foo
{
public:
    Foo(Bar* bar) { }
};
1

There are 1 answers

0
Alexander Balabin On BEST ANSWER

Yes to both. A function with signature

void acceptFoo(const Foo& foo)

will make the compiler to create a Foo if you pass a Bar there.

Same for 0 and nullptr.