c++abstract-classexplicit-constructor

Is there any reason to mark a constructor of an abstract class as explicit


In the following example, my class is abstract due to the abstract method run. I also have a constructor from another type. I always mark constructor having only 1 argument as explicit, except when I WANT implicit cast available. But, in the special case of an abstract class, is there any reason to justify it ?

class Foo
{
  public:
    virtual void run() = 0; // Then the class is abstract
    explicit Foo(Bar const& bar);
};

Note: my question is purely technical: is there any way to have a different behaviour with or without the explicit keyword on a constructor of an abstract class ?


Solution

  • But, in the special case of an abstract class, is there any reason to justify it ?

    If you use copy-list-initialization and inheriting constructors, it prevents some implicit conversions.

    class Fuzz : public Foo {
        using Foo::Foo;
        void run() override {} 
    };
    
    Bar b;
    Fuzz f = {b}; // Error when Foo's c'tor is explicit
    

    Now this is pretty specific, but if your goal is to prevent implicit conversions, and given how complicated C++'s initialization rules are, better be consistent and explicit.