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 18

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 18 - 24 lines .
  • At line 27 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 28 and 29) are the same as the ones set in the default constructor (lines 22 and 23).

Parameterized Constructor

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

Syntax for parameterized constructor:

Syntax of creating objects using parameterized constructor:

Example of class using parameterized constructors

Output:

Explanation:

  • At lines 35 - 41 there is a constructor accepting two parameters.
  • The constructor with two parameters is used at line 46 and thus "Parametrized constructor." is printed (due to line 37).

Defining constructor via __construct keyword

Except a function with same name as the class, a __construct function can be used for defining constructors.

Example:

Output: