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:
- have the constructor throw an exception, and have handlers in the calling function to handle it.
- have a flag in the class and set it to true only if the values are acceptable by the constructor, and have the program check the flag immediately after construction.
- have a separate (probably static) function to call to check the input parameters immediately before calling the constructor.
- redesign the class so that it can be constructed from any input parameters.
Which of these methods is most common in industry? Or is there anything I may have missed?