Why do constructors not return values?

Constructor

Constructor Problem Overview


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.

Constructor Solutions


Solution 1 - Constructor

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.

Solution 2 - Constructor

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

Solution 3 - Constructor

(I'm biased towards C++, so regarding other languages, take this with a grain of salt.)

Short answer: You don't want to have to explicitly check for success for every single object construction in your code.

Somewhat longer answer: In C++, constructors are called for dynamically as well as for globally and automatically allocated objects. In this code

void f()
{
  std::string s;
}

there is no way for the constructor of s (std::string::string()) to return any value. Either it succeeds - then we can use the object, or it throws an exception - the we never get a chance to try to use it.

IMO, that's the way it should be.

Solution 4 - Constructor

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?

Solution 5 - Constructor

A constructor is some method automatically called when you initialize a new instance of an object.

This method is there if you need to initialize your object to a given state and run few default methods.

Actually you can imagine the constructor always return the instance of the object created that would be a good image.

Solution 6 - Constructor

When you call a constructor the return value is the new object:

Point pt = new Point(1,2);

But within the constructor itself, you're not actually creating and returning the object; it's been created before your code starts, you're just setting up the initial values.

Point::Point(int x, int y) {
  this->x = x;
  this->y = y;
}

The lack of a return type reflects the fact that constructors are used differently than other functions. A return type of null, while technically accurate, doesn't reflect well the fact that the code is used as if it returns an object. However, any other return type would indicate that your code is supposed to return something at the end, which is also incorrect.

Solution 7 - Constructor

all answers are biased towards C++/Java. there is no reason a constructor does not return a value other than the language design.

look at a constructor in a broader sense: it is a function which constructs a new object. you can write perfectly valid constructors in C:

typedef struct object object;
int object_create( object **this );

this is perfect OOP in C and the constructor returns value (this can also be called a factory, but the name depends on the intention).

however, in order to create an object automatically (to satisfy some type cast, or conversion for example), there have to be some rules defined. in C++, there is an argument-less constructor, which is inferred by the compiler if it is not defined.


the discussion is broader than what we think. Object Oriented Programming is a name which describes a way of thinking about programming. you can have OO in almost any language: all you need is structures and functions. mainstream languages like C++ and Java are so common that we think they define "the way". now look at the OO model in Ada: it is far from the model of C++ but is still OO. i am sure languages like Lisp have some other ways of doing OO.

Solution 8 - Constructor

One point that hasn't yet been discussed is that the constructor of class "foo" must be usable not only when creating instances of foo, but also when creating instances of classes derived from foo. In the absence of generics (which weren't available when Java, C++, or .net were designed) there would be no way for foo's constructor to return an object of any derived class. Therefore, what needs to happen is for the derived-class object to be created via some other means and then made available to foo's constructor (which will then be able to use the object in question as a foo when doing its initialization).

Solution 9 - Constructor

Even though the VM implementation of a constructor isn't to return any value, in practice it kind of does - the new object's reference. It would then be syntactically weird and / or confusing to be able to store one or both of the new object's reference and an additional return value in one statement.

Solution 10 - Constructor

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.

Solution 11 - Constructor

Constructor is not directly called by the user's code. It's called by the memory allocation and object initialization code in the run time. Its value is not visible to the user.

Solution 12 - Constructor

Constructor doesn’t return anything not even Void. Though some of the answers have mentioned that Constructor do return reference to the newly created object , which is not true. It’s the new operator that returns the object.

So Why constructor doesn’t return any value

Because its not supposed to return anything. The whole purpose of constructor is to initialize the current state of the object by setting the initial values.

So Why doesn’t it even return Void

This is actually a Design constraint which has been placed to distinguish it from methods. public void className() is perfectly legal in java but it denotes a method and not a constructor. To make the compiler understand that it’s a constructor , it requires a way to distinguish it.

Solution 13 - Constructor

In case of C#, the syntax for declaring object is :

classname objectname= new constructor();

According to this line, if we are using assignment operator(=) then it should return some value. But the main objective of a constructor is to assign values to variables, so when we use a new keyword it creates instance of that class, and constructor assigns values to the variable for that particular instance of object, so constructor returns assigned values for that objects's instance.

Solution 14 - Constructor

We can not call constructors independently. Instead they are automatically called whenever objects are created. Ex:

MyDate md = new Mydate(22,12,2012);

In above example new will return a memory location which will be held by md, and programatically we can not return multiple values in single statements. So constructors can not return anything.

Solution 15 - Constructor

From what I know about OO design methodologies, I would say the following:

1)By allowing a constructor to return a value, framework developer would allow the program to crash in an instant where the returned value is not handled. To keep the integrity of the program workflow, not allowing a return value from the initialization of an object is a valid decision. Instead, language designer would suggest/force the coders to use getter/setter - access methods.

2)Allowing the object to return a value on initialization also opens possible information leaks. Specially when there are multiple layer or access modifications applied to the variables/methods.

Solution 16 - Constructor

As you aware that when object is created constructor will be automatically called So now imagine that constructor is returning an int value. So code should like this...

Class ABC
{
     int i;
public:
     int ABC()
     {
        i=0;
        return i;
     }
     .......
};
int main()
{
    int k= ABC abc; //constructor is called so we have to store the value return by it
    ....
}

But as you aware that stament like int k= ABC abc; is not possible in any programming language. Hope you can understand.

Solution 17 - Constructor

i found it helpful

This confusion arises from the assumption that constructors are just like any other functions/methods defined by the class. NO, they are not.

Constructors are just part of the process of object creation. They are not called like other member functions.

Solution 18 - Constructor

I would be using Java as my language in the answer.

class SayHelloOnCreation {
     public SayHelloOnCreation() {
         System.out.println("Hello, Thanks For Creating me!");
     }
}

class Test {
     public static void main(String[]args) { 
         SayHelloOnCreation thing = new SayHelloOnCreation(); //This line here, produces an output - Hello, Thanks For Creating me!
     }
}

Now let us see what is happening here. in java, we use the new keyword to create an instance of a class. And as you can see in the code, in the line, SayHelloOnCreation thing = new SayHelloOnCreation();, the expression after the assignment operator runs before assignment is done. So using the keyword new, we call the constructor of that class (SayHelloOnCreation()) and this constructor creates an object on the Java Heap. After the object is created, a reference to that object is assigned to the thing reference of type SayHelloOnCreation.

The point that I am trying to keep here is that if constructors were allowed to have a return type, Firstly the strongly typed nature of the language would be compromised (Remember I am speaking about Java here).

Secondly, an object of class SayHelloOnCreation is created here so by default I guess the constructor returns a reference of the same type, to avoid ClassCastException.

Solution 19 - Constructor

A method returns the value to its caller method, when called explicitly. Since, a constructor is not called explicitly, who will it return the value to. The sole purpose of a constructor is to initialize the member variables of a class.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDr. Rajesh RolenView Question on Stackoverflow
Solution 1 - ConstructorDathanView Answer on Stackoverflow
Solution 2 - ConstructorThiloView Answer on Stackoverflow
Solution 3 - ConstructorsbiView Answer on Stackoverflow
Solution 4 - ConstructorEricSchaeferView Answer on Stackoverflow
Solution 5 - ConstructorRageZView Answer on Stackoverflow
Solution 6 - ConstructortylerlView Answer on Stackoverflow
Solution 7 - ConstructorAdrien PlissonView Answer on Stackoverflow
Solution 8 - ConstructorsupercatView Answer on Stackoverflow
Solution 9 - Constructoruser4060017View Answer on Stackoverflow
Solution 10 - ConstructorAhmed SalimView Answer on Stackoverflow
Solution 11 - ConstructorTony StarkView Answer on Stackoverflow
Solution 12 - ConstructorRakibul IslamView Answer on Stackoverflow
Solution 13 - ConstructorsamruddhiView Answer on Stackoverflow
Solution 14 - ConstructorRoshanView Answer on Stackoverflow
Solution 15 - ConstructorOzan AksoyView Answer on Stackoverflow
Solution 16 - ConstructorKamlesh MkavanaView Answer on Stackoverflow
Solution 17 - ConstructorSamiullah BangashView Answer on Stackoverflow
Solution 18 - ConstructorN. PamnaniView Answer on Stackoverflow
Solution 19 - Constructoruser13993978View Answer on Stackoverflow