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 22
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:
19 - 25 lines
.line 32
an object is created via the default constructor.
The code of the default constructor executes and "Object creation." is printed.lines 34 and 35
) are the same as the
ones set in the default constructor (lines 23 and 24
).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:
lines 30 - 35
there is a constructor accepting only one parameter.
At lines 38 - 44
there is a constructor accepting two parameters.line 58
and thus
"Constructor with 1 parameter." is printed (due to line 32
).line 59
and thus
"Constructor with 2 parameters." is printed (due to line 40
).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:
line 59
an object named person_1
is created via parameterized constructor.
line 63
an object named person_2
is created via copy constructor.
This triggers the code at lines 39 - 45
.
It duplicates the passed as parameter person_1
object.