Constructors
Constructor functions are the special functions which if present automatically get executed whenever an object of a class is declared.
Properties
• Name of the constructor function is exactly same as that of the class.
• It has no return type not even void
• If present it automatically gets executed whenever an object of a class is declared
• It cannot be invoked/called using an object of the class.
• It is generally used to initialize the data elements of an object at the time of declaration.
There are three types of constructors
• Default constructors
• Parameterized constructors
• Copy constructors
Default constructors
Default Constructor is a special function which if present automatically gets executed whenever an object of a class is declared without any parameters.
Example:
student s;
employee e;
Properties
• Name of the default constructor function is exactly same as that of the class.
• It has no return type not even void
• If present it automatically gets executed whenever an object of a class is declared without any parameters.
• It cannot be invoked using an object of the class.
• It is generally used to initialize the data elements of an object at the time of declaration by user-defined values.
• We do not pass any arguments in the default constructor.
• Default constructor cannot be overloaded.
• Default constructors gets called only once for an object when it is declared without parameters.
Question:
How many default constructors can be present in a class? Why?
Sol:
There can be only one default constructor in the class.(the reason we do not pass any arguments to a default constructor and hence cannot be overloaded).
Question:
Why default constructors cannot be overloaded? Give reason.
Sol:
As we do not pass any arguments to a default constructor and so cannot be overloaded.