Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does access control matter for deleted constructors?

Is there a difference in behavior between whether an explicitly deleted constructor is public, protected or private?

For example, a non copyable class would have a deleted copy constructor (and deleted copy assignment). The constructor would not be available to neither subclasses (or friends) nor to outside users of the class, because it doesn't exist, regardless of its access control.

The only difference I see would be in what manner different scopes would see that the copy constructor doesn't exist - whether it is just not there (as far as that scope knows) or it is explicitly deleted.

Now, it might be beneficial to have the best formal interface for the class - that is, if everyone should know that the class is non-copyable, it should be publicly deleted. Compiler error messages might also be more informative. But other than that - would there be any actual observable difference in the class behavior? That is, something one could do with a class which has its deleted constructor with access X which he couldn't do if that constructor had access Y?

like image 391
Danra Avatar asked Mar 06 '23 11:03

Danra


1 Answers

Since it's overload resolution that makes the program ill-formed in this case, and not access specifiers (which are checked later), there is no difference in outcome. The compiler will always complain that a deleted function was picked.

But since the idiom before C++11 was "declare but not define a private copy c'tor to disable copying", I would consider it going along with the same idiom, and therefore favorable. You are using the "old slang" with some new language to describe the same thing, except better.

like image 53
StoryTeller - Unslander Monica Avatar answered Mar 10 '23 13:03

StoryTeller - Unslander Monica