View Full Version : constructors, new, return

29th September 2006, 14:28
Hello all,
I think a widget constructor in Qt will return a zero pointer if construction can't be done. Is that right? Well, how is that done?

AThing* myThing = new AThing(someParameters);
if(myThing)//check to see if made correctly

When I try to return anything from my constructors I get a compiler error - can't return a value. new() is doing the work here and is returning the pointer, no? Can I get my constructor to get a zero pointer (or any other value) returned from new()?

In the above example AThing() needs a port, or a file, or some memory, which it can't get. After the construction, I can check with some func e.g.
bool myThing->constructedProperly() but maybe my object failed to allocate enough memory for itself so that I can't even call that func.


29th September 2006, 14:43
It is "new" which returns a pointer to an object or 0 if it can't allocate memory for it, not the constructor. The latter only creates the object in the part of memory it is given. It is called by the compiler for both heap allocated (through operator "new") and stack allocated objects. You can't return values from the constructor, you can only throw exceptions or use some flags inside the object itself, which can then be checked from outside (like Qt does with isNull() or isValid() methods).