Home > Net >  Purpose of explicitly deleting the default constructor
Purpose of explicitly deleting the default constructor

Time:04-06

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?

CodePudding user response:

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.

  1. If someone changes the class to remove its constructors, the class won't suddenly gain a default constructor.

  2. 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 = default

    This 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.

CodePudding user response:

As became clear in the comments under the question, having a constructor (or a member function) declared but never implemented is bad design that leads to bad error messages. The only justified reason to = delete something that would not have been generated anyways, is documenting explicit intent. In my case, none of the classes gives the impression that it should have a default construtor.

I’m still not sure what’s ideal in my case because that depends on who’s going to work on the code base in the furute. For now, I’ll continue to change private never-defiend to = delete, but leave it at that. It’s rather easy to find = delete constructors and replace them with nothing compared to restoring them after they’re removed.

  • Related