Having a default constructor is optional, but it often makes use of your class easier in some situations. If you don't provide any constructors, then the compiler will generate a default constructor for you which is equivalent to one with an empty initializer list and an empty function body.
When implementing a default constructor, it's usually best to make it as efficient as possible as frequently of default constructor is not used or overwritten. E.g. Streaming: T t; std::cin >> t;
or creating a fixed array of things to be re-assigned later T arr[100];
. For this reason, while it might seem obvious to make the default constructor set a DateTime
to "now", if this involves a system call or other expensive operation to find out the current date it is usually better not to do this for a default constructor.
If you had no constructors at all, then there are many situations where value-initialization would cause all your members to be initialized in any case, e.g.:
// Explicit value-initialzation of dynamcially allocated DateTime
DateTime* pdt = new DateTime();
// Value-initialized temporary
FunctionTakesDateTime( DateTime() );
// Copy-initalization from a value-initialized temporary
DateTime dt = DateTime();
If you supplied a default constructor but didn't explicitly initialize all the members of the class and those members were of POD-type (like time_t
and int
) then those members would now be left uninitialized. To get the same effect for value-initialization as if you had no user-declared constructors you would have to explicitly initialize all your members in your default constructor.
DateTime() : ticks(), days(), months() /*, ... */ {}
This would be my preferred default constructor implementation. It means that default construction is still fairly cheap, but default constucted DateTime
s still have a well defined and easily recognizable value for debugging and diagnostic purposes.
While you can have an initialized
boolean, allowing you to have "delayed construction", I wouldn't recommend it. It adds a lot of overhead to all the rest of the class design with what would probably be very little gain. If a client wants to manipulate DateTime
with non-default values then it should be up to the client to initialize them as required.