tags:

views:

299

answers:

7

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

+3  A: 

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
So why shouldn't that method not be allowed to return `null`? I'm not convinced. Not at all.
sbi
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
+2  A: 

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
"How is a constructor supposed to return a return value?" It could return `this`. Failed construction would be indicated by returning `null`.
sbi
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
Nice choice for an integer.
Austin Kelley Way
@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
+1  A: 

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
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
let's say the compiler call the good constructor for you.
RageZ
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
@Johannes: Good point!
RageZ
+6  A: 

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.

Dathan
very good answer
Rajesh Rolen- DotNet Developer
Can we assume you are describing .NET?
ChaosPandion
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
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
+1  A: 

(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
A: 

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
A: 

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