I know constructors don't "return" anything but for instance if I call CMyClass *object = new CMyClass()
is there any way to make object to be NULL if the constructor fails? In my case I have some images that have to be loaded and if the file reading fails I'd like it to return null. Is there any way to do that?
Thanks in advance.
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.
No, constructor does not return any value.
Constructor is not like any ordinary method or function, it has no return type, thus it does not return void. Constructors don't create objects.
The constructor cannot return value, But you can handle it differently. Nice, exactly what I needed! I was going to recommend this approach but the only thing I'd have to add is that this approach is called Factory Pattern .
I agree with everyone else that you should use exceptions, but if you do really need to use NULL for some reason, make the constructor private and use a factory method:
static CMyClass* CMyClass::create();
This means you can't construct instances normally though, and you can't allocate them on the stack anymore, which is a pretty big downside.
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