Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a constructor return a NULL value?

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.

like image 274
Sanctus2099 Avatar asked May 18 '10 16:05

Sanctus2099


People also ask

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.

Can a constructor return a value?

No, constructor does not return any value.

Can a constructor return a void?

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.

Can a constructor return null C#?

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 .


1 Answers

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.

like image 178
Michael Mrozek Avatar answered Oct 19 '22 04:10

Michael Mrozek