Constructors

Constructor is used to create objects. It is a function that executes when object is created.

There are different types of constructors.

Syntax

Defining constructor:

Default 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:

  • The default constructor is defined at lines 2 - 6.
  • At 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.

Parameterized 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:

  • At lines 2 - 6 a parametrized constructor is defined.
  • At line 12 an object is created via the parametrized constructor.