I don't want to make it possible in my program to create an object without passing arguments to the constructor.
Is there a way?
Deleting the default constructor of a class is a good idea when there are multiple choices for the default or uninitialised state. For example, suppose I have a class, template<typename F> class Polynomial; which represents a polynomial over a field, F .
The compiler doesn't ever enforce the existence of a default constructor. You can have any kind of constructor as you wish. For some libraries or frameworks it might be necessary for a class to have a default constructor, but that is not enforced by the compiler.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
What is the significance of the default constructor? They are used to create objects, which do not have any specific initial value. Is a default constructor automatically provided? If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.
While the other answers are true, there is a new technique in C++11 for expressing that : deleted default constructor
It allows forbidding a function without depending on any other trick. It also clearly express your intention in the code.
class X { public: X(int) {} X() = delete; // will never be generated }; int main() { X x; // will not compile; X y(1); // will compile. return 0; }
When you declare any other constructor, the compiler will not generate the default constructor for you. If you have specified a default no-argument constructor, you can make it private.
Remember that the compiler can automatically generate each of these 4 member functions for a class.
But it will not generate a default one if you have declared one yourself, i.e., if you declared a constructor yourself, it will not create the default constructor. If you didn't declare any of the other 3 though, the compiler can generate them.
edit: Note that this information applies to C++03, but it is different in C++11 as Matthieu M. mentions in the comments. C++11 also allows for the constructor to be explicitly forbidden. See Offirmo's answer.
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