In: Computer Science
What is a constructor ? What is a destructor?
What is a default constructor? Is it possible to have more than one default constructor?
Constructor:
Constructor is also a member method, which is meant for allocating memory for the instance variables of the class, thus creating an object of the class. In other words, Constructor is a method for creating a new object.
The Constructor should have the same name as that of the class and it can be non-parameterized or parameterized. The purpose of the constructor is to assign initial values to the instance variables of the class.
The method header of a Constructor is different from an instance method by two ways:
(i) Constructor should not have any return type mentioned, not even void
(ii) The Constructor name should be the class name.
Destructor:
Destructor is also a member method of a class that is used to free the allocated memory resources of an object. Once the lifetime of an object is over or in other words, when the scope of the object is terminated, the destructor helps to free the object from memory.
Default Constructor
A default Constructor is a non-parameterized constructor which assigns default values to all the instance variables of the object, thus intializing the object once it is created.
It can also be parameterised in language like C++ where all parameters should assign default values to the instance variables.
Even if no constructors are defined for a class, the compiler implicitly uses a non-parameterized constructor which assigns default values to all the instance variables of the class. That is the default constructor.
Default Constructor can also be given in a class as mentioned above, either as a non-parameterized Constructor or parameterized with all parameters having default vaues
Yes, It is possible to have more than one default Constructor( in C++) where one can be a non-parameterized Constructor and the other can be parameterized with all parameters having default vaues,.
Language like Java, there is only one Default Constructor