The codebase I’m working on was developed mostly pre-C++11. A lot of classes have a never-defined default constructor declared in the private section. I’m rather confident that in Modern C++, the Correct Way™ is to make them public and = delete them. I “upgraded” classes to this countless times by now and it never lead to problems.
My question is rather: Why was that done at all? This answer said that a default constructor is only ever provided if there’s no constructor given by the user (I guess that’s not including = default) and there’s no hint that it doesn’t apply to pre-C++11. Of course, there is a non-trivial constructor in all of my classes I’m talking about. So, is there a rationale for it that I am missing?
>Solution :
Any function can be = deleted. A default constructor is a function, so it can be deleted. There’s no need to make a language carveout for that.
That some users choose to explicitly delete the default constructor (or the pre-C++ pseudo-equivalent of a private declaration with no definition) when it would not have been generated by the compiler is harmless. Indeed, it has some small benefits.
-
If someone changes the class to remove its constructors, the class won’t suddenly gain a default constructor.
-
You don’t have to remember what the rules are about when a default constructor is generated. For example:
I guess that’s not including
= defaultThis proves my point, because you guessed wrong. Explicitly
defaulted constructors do count as "user-provided", and thus they do suppress the creation of an implicit default constructor. Having to remember that is bothersome; it’s more clearer to just state it outright.