Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a default constructor

I am trying to implement a DateTime class in C++:

class DateTime {
public:
    DateTime();
    DateTime(time_t ticks);
    DateTime(int day, int month, int year);
    DateTime(int day, int month, int year, int hour, int minute, int second);
    //...

private:
    time_t ticks;
    int day;
    int month;
    //...
}

then in application:

DateTime date1; //default constructor

I know that having a default constructor is required for c++, but how should I implement it in this situation?

Should it set all properties to 0? That would make all other methods work, but doesn't really seem intuitive...

Should it just leave all properties un-initialized? That would make none of its methods work, but it seems more intuitive than 0, because you haven't done anything to it yet.

Should it set an internal bool initialized=false then all methods check that before operating on it?

I'm not really sure on this one. Is there a "standard" way of doing it?

like image 423
Austin Hyde Avatar asked Dec 01 '22 06:12

Austin Hyde


1 Answers

Typically, the default constructor would initialize you to a "default" reference time.

If you're using a time_t internally, setting it to time_t of 0 (Unix epoch, which is 1/1/1970) would be a reasonable option, since "0" values are common defaults.

That being said, a default constructor is not required in C++ - you can have a type with no default constructor, which would require a valid "time" to be specified.

like image 101
Reed Copsey Avatar answered Dec 04 '22 14:12

Reed Copsey