0

I have a class called Date that holds the month, day, year, and weekday of a date. I'd like to include in the class a static variable that represents the current date, but the process for initializing it requires multiple steps. I thought about initializing it in the constructor, but the client code may want to reference it before constructing a Date object. What is the best way to handle this?

The Date class:

class Date { 
        private: 
                // Date variables 
                unsigned int day; 
                unsigned int month; 
                unsigned int year; 
                unsigned int weekday; 

        public: 
                Date() = default; 
                Date(unsigned int, unsigned int, unsigned int); 

                void add_days(unsigned int);                     

                // Maintain static const info on current date 
                static const Date current_date; 

                // Getter and setter methods 
                unsigned int get_day(); 
                unsigned int get_month(); 
                unsigned int get_year(); 
                unsigned int get_weekday(); 

                void set_day(); 
                void set_month(); 
                void set_year(); 
};

The code to initialize current_date:

time_t raw_time = time(0);
tm current_tm;
localtime_s(&current_tm, &raw_time);
Date temp(current_tm.tm_mon, current_tm.tm_mday, current_tm.tm_year);
temp.weekday = current_tm.tm_wday;
const Date Date::current_date = temp;

Thank you for any suggestions.

enivium
  • 150
  • 1
  • 10
  • 1
    Since the current date can change, why not use a function that returns it? You can call it, `now()`. – David Schwartz May 11 '19 at 23:16
  • Possible duplicate of [Static member object of a class in the same class](https://stackoverflow.com/questions/10874317/static-member-object-of-a-class-in-the-same-class) – BattleTested_закалённый в бою May 11 '19 at 23:18
  • @DavidSchwartz Would that cause problems if client code doesn't call `now()` before trying to reference `current_date`? Is there a way I could enforce that? – enivium May 11 '19 at 23:20
  • 1
    @enivium Just get rid of `current_date`. The idea that the current date never changes is just wrong. Provide a `now()` function that returns the current date. (If you want to keep a `current_date` to avoid re-computation just make it private and let `now()` use it if you want to.) – David Schwartz May 11 '19 at 23:21
  • @DavidSchwartz I see what you're saying. I'll give that a try. Thanks! – enivium May 11 '19 at 23:24

0 Answers0