Does Constructor Return Any Value?

To find out whether constructor returns any value or not, let’s learn about a constructor?

In simple terms, the constructor is a special method, which is used to initialize an instance of a class. This special method differs from the actual methods of classes. The name of a constructor is always similar to the name of the class. Below is an example of a constructor:

How Constructor Work?

Consider an example:


Hello constructor

The object is built with the same name as the class name that is Student. The output to this code block is “Hello Constructor,” a pass to the name in the constructor’s initialization. This signifies that as the object obj builds, the constructor is invoked. This keyword represents the current object; here, the object is “obj.” The new keyword generates the object for the class and calls the constructor to define the object’s memory.

Now, let’s see the different types of constructors that you can make. There are three types of constructors:

1. Default Constructor: The objects with no arguments and statements invoke default constructors. All the values remain the same as they were assigned in the data members.

2. No-arg Constructor: The object with no argument but with some statements written inside it invokes the No-argument constructor.

3.Parameterized Constructor: The constructor that has one or more arguments falls under this category.

Does Constructor Return Any Value?

One of the main difference between constructor and method is that constructors do not return any value. In simpler terms, the constructor cannot use the return type. The reason is that you don’t need to return any value.

The purpose of a constructor is to initialize an object. It assigns value to the data members, not return them. So, it does not need to return anything. Moreover, the constructor is called only once. 

What would happen if you put the return type to the constructor? For example:

This will show a compile-time error. This proves that constructors do not return any value.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *