Constructor is used to create objects. It is a function that executes when object is created.
There are different types of constructors.
Defining constructor:
Default constructor does not accept any arguments. It can be used without defining it.
If defined it sets default values to class members.
Example of default constructor usage without defining it:
Output:
An object is created via default constructor at line 4
.
Example of defining and using default constructor:
Output:
Explanation:
lines 2 - 6
.line 13 and 16
an object is created via the default constructor.
The code of the default constructor executes and "Object creation." is printed.person1
object does not overwrite name
and age
.
It's properties
have the same values as those set in the default constructor.The parameterized constructor accepts parameters which usually are used to set value for the object's members.
Example of class using parameterized constructor:
Output:
Explanation:
lines 2 - 6
a parametrized constructor is defined.line 12
an object is created via the parametrized constructor.