When/why would I want to explicitly delete my constructor? Assuming the reason is to prevent its usage, why not just make it private
?
class Foo { public: Foo() = delete; };
A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.
Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
In your code, the program cannot run since you have defined a constructor and it is private. Therefore, in your current code, there is no way to create objects of the class, making the class useless in a sense.
How about:
//deleted constructor class Foo { public: Foo() = delete; public: static void foo(); }; void Foo::foo() { Foo f; //illegal }
versus
//private constructor class Foo { private: Foo() {} public: static void foo(); }; void Foo::foo() { Foo f; //legal }
They're basically different things. private
tells you that only members of the class can call that method or access that variable (or friends of course). In this case, it's legal for a static
method of that class (or any other member) to call a private
constructor of a class. This doesn't hold for deleted constructors.
Sample here.
why explicitly delete the constructor?
Another reason:
I use delete
when I want to assure that a class is called with an initializer. I consider it as a very elegant way to achieve this without runtime checks.
The C++ compiler does this check for you.
class Foo { public: Foo() = delete; Foo(int bar) : m_bar(bar) {}; private: int m_bar; }
This - very simplified - code assures that there is no instantiation like this: Foo foo;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With