This may seem like an odd question. I’m currently moving certain objects from a two-step to a one-step initialization scheme. Basically moving what was done in the .initialize() .terminate() member functions into the constructors and destructors.
My issue is that, it is important to know whether or not these classes initialized certain attributes correctly that depend on external factors.
An example is my Window class which creates a WinAPI window. Previously using the two step method I would have initialize() return a boolean of whether or not the window was created properly.
if(myWindow.initialize())
{
// proceed with application
}
else
{
// exit
}
Is there anyway to relay this information from the constructor without creating and having to call a second method, such as didMyWindowInitializeCorrectly()?
At first I was hoping something along the lines of
if(Window *myWindow = new Window)
{
// proceed with application
}
else
{
// exit
}
But this won’t work because the Window object will still instantiate even though the window creation failed.
Is the only solution to have the constructor throw an exception and then catch it and proceed? I’ve looked at a lot of threads and people’s opinions of C++ exceptions seems pretty split so I’m unsure of what is the best approach.
Is there anyway to handle this situation with an if statement?
This comes down to the big argument of Exception or error code based initialization. I usually prefer Exceptions for indicating constructor failure as the problem becomes more apparent earlier in a stack trace when the problem isn’t handled over is_valid checks later in code or ignoring two-step return values. It’s also clearer about why initialization failed without needing error code lookups. People who prefer the conventional C style over Exception style failure messaging will probably disagree with me on that last point.
However, it’s oftentimes a good idea to match the style of the rest of the code base. So if Exceptions aren’t used anywhere else in the code, it’s probably better to have a is_valid check (or the original two stage initialization) over introducing a mechanism for object validation. I prefer the is_valid over two stage much like Riateche posted, as it leaves the user capable of choosing if/when they want to check it’s valid without needing for them to go lookup what functions have to be called before they should legally use the object.