34

I recently came across some weird looking class that had three constructors:

class Class
{
    public:
        explicit Class(int );

        Class(AnotherClass );

        explicit Class(YetAnotherClass, AnotherClass );

    // ...
}

This doesn't really make sense to me - I thought the explicit keyword is to protect compiler chosen construction from a foreign type.

Is this allowed? If it it, what does it mean?

Enlico
  • 23,259
  • 6
  • 48
  • 102
LiraNuna
  • 64,916
  • 15
  • 117
  • 140
  • 1
    this duplicate got more/better answers: [Why is explicit allowed for default constructors and constructors with 2 or more (non-default) parameters?](https://stackoverflow.com/questions/4467142/why-is-explicit-allowed-for-default-constructors-and-constructors-with-2-or-more) – underscore_d Jul 25 '17 at 10:33

1 Answers1

54

In C++11 multi-parameter constructors can be implicitly converted to with brace initialization.

However, before C++11 explicit only applied to single-argument constructors. For multiple-argument constructors, it was ignored and had no effect.

NuPagadi
  • 1,410
  • 1
  • 11
  • 31
Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
  • 1
    Thanks for clarification. I'd figure GCC would warn for such an occasion. – LiraNuna Jul 13 '09 at 10:27
  • 26
    With the caveat that if all but one of the multi-arg params have default values then it will have an effect – zebrabox Jul 13 '09 at 10:28
  • 20
    This has changed with C++11. Now multi-parameter constructors can be implicitly converted to with brace initialisation. – Shane Oct 02 '12 at 18:59
  • 2
    In addition to Shane's comment about C++11: see http://stackoverflow.com/a/4467658 – gx_ Sep 19 '13 at 12:58