Can a constructor return a NULL value?

24,461

Solution 1

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.

Solution 2

Constructors do not return values. They initialize an object and the only way of reporting errors is through an exception.

Note that the constructor does not make any type of memory management. Memory is allocated externally and then the constructor is called to initialize it. And that memory can be dynamically allocated (type *x = new type;) but it might as well be in the stack (type x;) or a subobject of a more complex type. In all but the first case, null does not make sense at all.

Solution 3

The "correct"** way is to throw an exception.

** You can provide a member function like is_valid that you can check after constructing an object but that's just not idiomatic in C++.

Solution 4

The way to do this is if you find something not working in your constructor you should throw an exception. This is what happens if C++ cannot allocate memory for your object - it throws std::bad_alloc. You should use std::exception or a subclass.

Solution 5

Could use a static factory method instead? When converting between types, I might make a public static CMyClass Convert(original) and return null if original is null. You'd probably still want to throw exceptions for invalid data though.

Share:
24,461
Sanctus2099
Author by

Sanctus2099

I love programming, I love OpenGL and GLSL. I'm currently working on my own game engine and it's turning out nicer than most available products.

Updated on August 16, 2020

Comments

  • Sanctus2099
    Sanctus2099 almost 4 years

    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.