Search code examples
c++instantiationexplicit-conversion

C++ explicit constructor that takes a pointer


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);
}

Solution

  • 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