Search code examples
c++default-constructorexplicit

Does "explicit" keyword have any effect on a default constructor?


Is there a reason to use the explicit keyword for a constructor that doesn't take any arguments? Does it have any effect? I'm wondering because I just came across the line

explicit char_separator()

near the end of the page documenting boost::char_separator, but it's not explained any further there.


Solution

  • Yes, it does have an effect.

    Compare:

    struct A
    {
        A() {}
    };
    
    void foo(A) {}
    
    int main()
    {
        foo({}); // ok
    }
    

    and:

    struct A
    {
        explicit A() {}
    };
    
    void foo(A) {}
    
    int main()
    {
        foo({}); // error
    }