Is constructor necessary in C++?
Is any constructor necessary in C++?
Collapse
X
-
PUTULTags: None
-
Not necessarily. It depends on your application.
If you don't write a constructor, the compiler supplies a default constructor which creates your object but doesn't do anything else.
If you want the member variables to be initialized, or if you want anything else done when the new object is created, then you have to write a constructor (or several constructors, depending on your requirements). -
If you don't write a constructor, the compiler supplies a default constructor which creates your object but doesn't do anything else.
Creating the object is independent from calling constructors.
If someone else designs a class with an object of your class as a member and then creates a object of their class using the compiler's default constructor, then your class must have a default constructor or their code won't compile.Comment
-
... then your class must have a default constructor ...
In that sense, "default constructor" simply means a constructor that takes no arguments. It may initialize data members or perform other functions.Comment
Comment