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 28

The name and age members have pretty weird values even for default ones. 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 24 - 30.
  • At line 37 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 39 and 42) are the same as the ones set in the default constructor (lines 28 and 29).

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 35 - 41 there is a constructor accepting only one parameter. At lines 44 - 51 there is a constructor accepting two parameters.
  • The constructor with one parameter is used at line 67 and thus "Constructor with 1 parameter." is printed (due to line 37).
  • The constructor with two parameters is used at line 68 and thus "Constructor with 2 parameters." is printed (due to line 46).

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:

There are a couple of things to notice:

  • At line 67 an object named person_1 is created via parameterized constructor.
  • At line 71 an object named person_2 is created via copy constructor. This triggers the code at lines 44 - 51. It duplicates the passed as parameter person_1 object.