I always thought that implicit constructor in C++ could only be a constructor with only one argument. For example:
class Foo1
{
Foo(int); // This could be an implicit constructor
};
But is the following code right:
class Foo2
{
Foo2(int, int=0); // Would compiler use this as an implicit constructor?
}
I can do this:
Foo1 obj;
...
obj = 5;
What about Foo2?
First, any constructor can be marked
explicit. How many arguments it has is irrelevant.With that out of the way, you just now need to understand what
explicitreally means. It just means that the only way that constructor can be called is when you explicitly specify the class name:The reason we don’t mark multiple-argument constructors explicit is because it’s useless. Given:
How else can you call that constructor other than saying
bazanyway? (As inbaz(1, 2, 3).)†In your example,
explicitwould be sensible because you could call that constructor with only one argument. What you actually do only depends on if you feel it should be implicitly convertible or not.†This is disregarding C++11 initializer lists. In C++11, I think you could say:
And manage to get an implicit conversion to a multiple-argument constructor, but I don’t know enough about initializer-lists to make a meaningful comment except as a footnote.