Constructors

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

There are different types of constructors.

Default Constructor

Default constructor can be used without defining it.

If defined it sets default values to class members.

Syntax of default constructor:

Syntax of creating object using default constructor:

Example of default constructor usage without defining it:

Output:

An object is created via default constructor at line 15.

The name member has pretty weird value even for default one (""). For this reason we can define default constructor to set default values.

Example of defining and using default constructor:

Output:

There are couple of things to notice:

  • The default constructor is defined at lines 11 - 17.
  • At line 24 an object is created via the default constructor. The code of the default constructor executes and "Object creation." is printed.
  • The printed name and age (lines 25 and 26) are the same as the ones set in the default constructor (lines 15 and 16).

Parameterized Constructor

The parameterized constructor accepts parameters which usually are used to set value for the object's members.

Also one class may have more than one parameterized constructors.

Syntax for parameterized constructor:

Syntax of creating objects using parameterized constructor:

Example of class using parameterized constructors:

Output:

There are a couple of things to notice:

  • At lines 11 - 16 there is a constructor accepting only one parameter. At lines 19 - 25 there is a constructor accepting two parameters.
  • The constructor with one parameter is used at line 40 and thus "Constructor with 1 parameter." is printed (due to line 13).
  • The constructor with two parameters is used at line 41 and thus "Constructor with 2 parameters." is printed (due to line 21).

Copy Constructor

Copy constructor is used to create a duplicate of an object. It accepts an object to duplicate as a parameter.

Syntax of defining a copy instructor:

Syntax of using copy constructor:

Example of copy constructor usage:

Output:

Explanation:

  • At line 41 an object named person_1 is created via parameterized constructor.
  • At line 45 an object named person_2 is created via copy constructor. This triggers the code at lines 22 - 25. It duplicates the passed as parameter person_1 object.