1

I've recently stumbled across an explicit constructor that receives a single pointer argument. I wonder if the explicit keyword is necessary in this case? as there is no constructor for a pointer so there cannot be any implicit conversion.

class Foo {
 public:
  explicit Foo(int* int_ptr);
}
AMT
  • 1,016
  • 1
  • 7
  • 13
  • 3
    Why would a pointer be different to any other constructor parameter? – juanchopanza Oct 10 '17 at 09:38
  • 2
    Whether `explicit` is necessary is a different matter, and has nothing to do with the parameter being a pointer. It has to do with which implicit conversions you want to allow. – juanchopanza Oct 10 '17 at 09:39

1 Answers1

7

The following code:

void f(Foo) {}

int main()
{
    int* p;
    f(p);
}
  • Fails to compile with explicit.

  • Happily compiles without it.

live example on godbolt.org

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416