Please note that this is asking a question about constructors, not about classes which handle time.
Suppose I have a class like this:
class Time { protected: unsigned int m_hour; unsigned int m_minute; unsigned int m_second; public: Time(unsigned int hour, unsigned int minute, unsigned int second); };
While I would want a to be constructed successfully, I would want the constructor of b to fail.
Time a = Time(12,34,56); Time b = Time(12,34,65); // second is larger than 60
However, this is not possible, because constructors do not return any values and will always succeed.
How would the constructor tell the program that it is not happy? I have thought of a few methods:
Which of these methods is most common in industry? Or is there anything I may have missed?
The best way to signal constructor failure is therefore to throw an exception. If you don't have the option of using exceptions, the "least bad" work-around is to put the object into a "zombie" state by setting an internal status bit so the object acts sort of like it's dead even though it is technically still alive.
It's not possible to use error code since constructors don't have return types.
If an exception is thrown in a constructor, the object was never fully constructed. This means that its destructor will never be called. Furthermore, there is no way to access an object in an error state. The exception will immediately unwind the local variable.
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
The typical solution is to throw an exception.
The logic behind that is the following: the constructor is a method that transforms a chunk of memory into a valid object. Either it succeeds (finishes normally) and you have a valid object or you need some non-ignorable indicator of a problem. Exceptions are the only way to make the problem non-ignorable in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With