Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty return in Constructor

I expected Visual Studio to give me an error or at the very least a warning, but it gave me neither when I had an empty return in the constructor:

MyObject::MyObject()
{
    if (/*some condition*/)
    {
        //SomeCode
        return;
    }

    // continue with other code
}

I have not seen usage of this so far in my limited experience, so my question is whether it is OK to have a return in the constructor?

This is more of a curiosity question as I understand that it is very easy to code such that you never have to put return in there, although I have an instance where this would be very useful, but before using it I want to see if it is prohibited (maybe by the standard or is, in general, not a good idea).

like image 764
Samaursa Avatar asked Nov 23 '10 00:11

Samaursa


People also ask

What does an empty return do?

It means it will return None . You could remove the return and it would still return None because all functions that don't specify a return value in python will by default return None .

Which constructor has no return?

Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type.

Can you use return in a constructor?

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.

Can a constructor return null?

Thanks In Advance !! We can not return any value from constructor... A constructor does not return anything; the "new" operator returns an object that has been initialized using a constructor. If you really want a constructor that may return null, perhaps you should check out the factory method pattern.


1 Answers

The standards say:

12.1 Constructors
...
A return statement in the body of a constructor shall not specify a return value. The address of a constructor shall not be taken.
...

It is OK to have return; in a constructor. My understanding is that this was allowed so that the programmer can return early from the constructor without the need for making a mess with boolean flags.

like image 121
Khaled Alshaya Avatar answered Oct 19 '22 17:10

Khaled Alshaya