In this lesson, the world of constructors is explored and you'll learn why they are necessary for a class.

What is a constructor?

As the name suggests, the constructor is used to construct the object of a class. It is a special method that outlines the steps that are performed when an instance of a class is created in the program.

A constructor’s name must be exactly the same as the name of its class.

The constructor is a special method because it does not have a return type. We do not even need to write void as the return type. It is a good practice to declare/define it as the first member method.

So, let’s study the different types of constructors and use them to create class objects.

Default constructor

The default constructor is the most basic form of a constructor. In a default constructor, we define the default values for the data members of the class. Hence, the constructor creates an object in which the data members are initialized to their default values.

This will make sense when we look at the code below. Here, we have a Date class, with its default constructor, and we’ll create an object out of it in our main():

Get hands-on with 1200+ tech skills courses.