Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do constructors not return values?

Tags:

constructor

Please tell me why the constructor does not return any value. I want a perfect technical reason to explain to my students why the constructor does not have any return type.

like image 792
Dr. Rajesh Rolen Avatar asked Nov 24 '09 06:11

Dr. Rajesh Rolen


People also ask

Does constructor return any value?

No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.

Why constructor have no return type in C++?

The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object which is why it is known as constructors. Constructor does not have a return value, hence they do not have a return type.

Which constructor Cannot have return value?

1 Answer. Explanation: Constructors don't return any value. Those are special functions, whose return type is not defined, not even void. This is so because the constructors are meant to initialize the members of class and not to perform some task which can return some value to newly created object.

Are constructors allowed to return?

A constructor cannot have a return type (not even a void return type). A common source of this error is a missing semicolon between the end of a class definition and the first constructor implementation.


2 Answers

What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory, be it on the stack or on the heap.

This space includes all members variables and the vtbl. After this space is allocated, the constructor is called as an internal part of the instantiation and initialization process to initialize the contents of the fields.

Then, when the constructor exits, the runtime returns the newly-created instance. So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime.

Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it.

like image 91
Dathan Avatar answered Sep 28 '22 04:09

Dathan


Well, in a way it returns the instance that has just been constructed.

You even call it like this, for example is Java

 Object o = new Something(); 

which looks just like calling a "regular" method with a return value

 Object o = someMethod(); 
like image 20
Thilo Avatar answered Sep 28 '22 04:09

Thilo