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).
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With