Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why constructors aren't explicit by default?

Tags:

c++

It's so easy to forget to mark a constructor "explicit": adding/removing args, making them optional etc. the single reliable way I know is to declare every constructor as explicit and then remove this keyword only if implicitness is required by design (thanks to the standard that allows this not only on single-argument constructors). But this would look ugly.

not intended implicit constructors open usage of (mistaken) implicit conversion, e.g. as here. this can happen by accident, or can break backward compatibility

so why "explicit" is not default characteristic of a constructor if this would lead to fewer bugs?

p.s. yeah, I read Stroustrup's "The Design and Evolution of C++", just don't remember if he says anything about "explicit" there

like image 680
Andriy Tylychko Avatar asked Jan 05 '11 17:01

Andriy Tylychko


3 Answers

Backward compatibility at the time when explicit was added. The language was evolving and changing meaning of existing constructs in an evolving language is a sure way to make your users angry. It is still the case now, backward compatibility is something high in the mind of the comittee.

like image 87
AProgrammer Avatar answered Sep 21 '22 06:09

AProgrammer


Because when C++ was conceived it was considered that nobody would write stupid code, and everybody would enjoy the benefits that nice implicit conversions would bring in avoiding having to write casts everywhere.

Of course, this turned out to be false, and really there are buggy constructors all over the place. Such a shame.

like image 23
Lightness Races in Orbit Avatar answered Sep 24 '22 06:09

Lightness Races in Orbit


Interesting vantage point. I would tend to take the other side, and wonder why you think you need to mark all your constructors explicit until proved otherwise?

Honestly I don't know the answer to your question, if there even is one. Backwards compatibility seems like it might be a contender for most-likely-reason, but again: why do you wish to prevent implicit conversion?

like image 38
John Dibling Avatar answered Sep 23 '22 06:09

John Dibling