Constructor is used to create objects. It is a function that executes when object is created.
There are different types of constructors.
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:
18 - 24 lines
.line 27
an object is created via the default constructor.
The code of the default constructor executes and "Object creation." is printed.lines 28 and 29
) are the same as the
ones set in the default constructor (lines 22 and 23
).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:
lines 35 - 41
there is a constructor accepting two parameters.line 46
and thus
"Parametrized constructor." is printed (due to line 37
).Except a function with same name as the class, a __construct
function can be used for defining constructors.
Example:
Output: