Search code examples
c++exceptionconstructor

How can I check the failure in constructor() without using exceptions?


All of the classes that I'm working on have Create()/Destroy() ( or Initialize()/Finalized() ) methods.

The return value of the Create() method is bool like below.

bool MyClass::Create(...);

So I can check whether initialization of the instance is successful or not from the return value.

Without Create()/Destroy() I can do the same job in constructor() and destructor() but I can't solve below problem.

Can anyone help me? Thanks in advance.

I cannot use exceptions because my company doesn't like it.

class Foo
{
private:
    AnotherClass a;
public:
    Foo()
    {
        if(a.Initialize() == false)
        {
            //???
            //Can I notify the failure to the user of this class without using exception?
        }
    }
    ...
};

Foo obj;

Solution

  • If you don't want to use exceptions, there are two ways to let the caller know whether the constructor succeeded or not:

    1. The constructor takes a reference/pointer to a parameter that will communicate the error status to the caller.
    2. The class implements a method that will return the error status of the constructor. The caller will be responsible for checking this method.

    If you go with either of these techniques, make sure your destructor can handle an instance where the constructor has failed.