Why do constructors not return values?

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.


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();

How is a constructor supposed to return a return value? The new operator returns the newly created instance. You do not call a ctor, newdoes it.

MyClass instance = new MyClass();

If the ctor would return a value, like so:

public int MyClass()
{
    return 42;
}

Where would you receive the integer?

Tags:

Constructor