Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

explicit non-single parameter constructor

Can anyone explain why does non-single parameter constructor marked as explicit compile? As far as I understand this is absolutely useless keyword here, so why does this compile without error?

class X
{
public:
    explicit X(int a, int b) { /* ... */}
};
like image 433
axe Avatar asked Nov 27 '13 13:11

axe


2 Answers

In C++03, and in this particular case, it makes no sense for a two parameter constructor to be marked explicit. But it could make sense here:

explicit X(int i, int j=42);

So, marking a two parameter constructor with explicit does not have to be an error.

In C++11, this use of explicit would prevent you from doing this:

X x = {1,2};
like image 111
juanchopanza Avatar answered Sep 30 '22 14:09

juanchopanza


Not entirely true.

In C++11, constructors with multiple arguments can be implicitly converted using brace initialisation.

like image 27
Bathsheba Avatar answered Sep 30 '22 15:09

Bathsheba