Hey,
Over the past few weeks I've experienced the same dilemma during coding:
If you want to use the constructor to initialize some class member variables (such as allocating memory), what is the best practice approach to deal with errors?
I prefer not working with exceptions in my code so I started wondering how one tells the caller that the initialization failed in the constructor. I guess the obvious solution would be to not perform any operations that could potentially fail in the constructor, but this would just lead to extra code when initializing the class:
As is evident from the code snippet above, the second example requires two lines of code compared to a single line in the first example. The last example is just a slight variation on the second example, although the initialization now takes place in the constructor whereas the success of the initialization is verified later on in the second function call.Code:// Allocate 1024 bytes of memory CFoo foo(1024); OR CFoo foo; if (!foo.Allocate(1024)) ... OR CFoo foo(1024); if (foo.InitFailed()) ...
When not using exceptions I guess there is no alternative to doing multiple function calls if you want to make sure the object was created and initialized successfully. The question, however, is which approach is the best to use...