99

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.

asthasr
  • 9,125
  • 1
  • 29
  • 43
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178

19 Answers19

129

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.

Baby
  • 5,062
  • 3
  • 30
  • 52
Dathan
  • 7,266
  • 3
  • 27
  • 46
  • Can we assume you are describing .NET? – ChaosPandion Nov 24 '09 at 07:10
  • 7
    As much as this is technically detailed and correct, a simple "it wasn't designed to do it" would suffice IMHO. Surely it wouldn't be impossible to design the runtime to return the return value of the constructor instead of the newly-created instance. It just doesn't make much sense and hence wasn't designed to do it. :) – deceze Nov 24 '09 at 07:12
  • 2
    I'm not so sure about .Net - the above is my understanding of the approach C++ takes. I'm sure .Net is very similar, except that the metadata generated by the compiler encompasses MUCH more than just the amount of space required to instantiate it (and c++ stores some metadata about type as well, but nothing on the scale supported by .Net). – Dathan Nov 24 '09 at 07:24
  • 1
    At least in C++, it would be impossible for the constructor to return the newly created object. It would have to make a copy, which means calling the copy constructor, and what would _it_ return? However, you could return a reference. Still, return to where exactly? – MSalters Dec 11 '13 at 16:11
  • Could we say tha same for `__del__`? – floatingpurr Jul 04 '16 at 11:42
  • @ Dathan Is my understanding correct ,if I put your words like this. "Since a normal function call is associated with an object,.i.e we know what type of value will be returned ,but the same thing is not applicable in case of a constructor ,the object is still under construction,hence no return type ". – Nihar Feb 19 '17 at 15:43
12

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();
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 2
    So why shouldn't that method not be allowed to return `null`? I'm not convinced. Not at all. – sbi Nov 24 '09 at 07:10
  • 5
    It makes using the constructor much easier if you know the only possible end states are "you have a Something instance" or "an exception is thrown". (We tried the whole "make the caller check every return value" thing with C.) Is there a benefit to having two orthogonal error reporting mechanisms the caller has to check each time, or are you proposing doing away with exceptions, too? – Ken Nov 24 '09 at 07:28
  • @sbi it does return `null` if the constructor has failed to build an instance – claudiodfc Nov 09 '22 at 15:09
  • @claudiodfc Not in C++, no. – sbi Nov 15 '22 at 21:12
4

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?

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
  • "How is a constructor supposed to return a return value?" It could return `this`. Failed construction would be indicated by returning `null`. – sbi Nov 24 '09 at 07:11
  • 4
    But 'this' has to already exist when the constructor starts to run. If your construction "fails", the 'this' is already allocated, and then what happens? Do you have a partially-constructed object? Should the destructor be called on it, or not? In C++, if you throw in the constructor, you're supposed to save enough state in the zombie object that it can clean up after itself; without an object, how's it do that? Or do you now have 2 completely independent error mechanisms for constructors? – Ken Nov 24 '09 at 07:24
  • @sbi Since you do not call the ctro directly, it can not return anything. The reference/pointer to the new instance is returned by `new`, not the ctor. – EricSchaefer Nov 24 '09 at 12:02
4

(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.

sbi
  • 219,715
  • 46
  • 258
  • 445
2

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.

RageZ
  • 26,800
  • 12
  • 67
  • 76
  • Well, given that you still need to declare *which* constructor has to run (by including the proper arguments) I don't think that really qualifies as "automatically" :-) – Joey Nov 24 '09 at 07:04
  • Well, given most OOPL's syntaxes I'd say since you still write the type name, the arguments and in some languages (Delphi, Eiffel) the contructor's name, daying the compiler calls it is akin to saying that the compiler calls a method when you're writing out the method call. – Joey Nov 24 '09 at 07:07
2

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.

tylerl
  • 30,197
  • 13
  • 80
  • 113
2

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.

Rakibul Islam
  • 325
  • 1
  • 3
  • 13
1

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.

Adrien Plisson
  • 22,486
  • 6
  • 42
  • 73
  • How would inheritance work in such a scenario? If the user-supplied code for a constructor accepts a reference to a presumably-blank `BaseType` object and sets it up as appropriate, such code will have no problem if it's given a `DerivedType` object instead. If the code returned a `BaseType` object, though, it's less clear how it could be used to produce a `DerivedType` object. – supercat Oct 25 '12 at 20:37
1

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.

1

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.

1

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.

Tony Stark
  • 265
  • 2
  • 16
1

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).

supercat
  • 77,689
  • 9
  • 166
  • 211
0

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.

Nikana Reklawyks
  • 3,233
  • 3
  • 33
  • 49
0

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.

tiago
  • 22,602
  • 12
  • 72
  • 88
Roshan
  • 1
0

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.

Ozan Aksoy
  • 306
  • 3
  • 6
0

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.

PakkuDon
  • 1,627
  • 4
  • 22
  • 21
0

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.

0

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.

N. Pamnani
  • 57
  • 1
  • 8
0

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.