Initializing static struct tm in a class

eruina picture eruina · Jan 20, 2010 · Viewed 13.6k times · Source

I would like to use the tm struct as a static variable in a class. Spent a whole day reading and trying but it still can't work :( Would appreciate if someone could point out what I was doing wrong

In my class, under Public, i have declared it as:

static struct tm *dataTime;

In the main.cpp, I have tried to define and initialize it with system time temporarily to test out (actual time to be entered at runtime)

time_t rawTime;
time ( &rawTime );
tm Indice::dataTime = localtime(&rawTime);

but seems like i can't use time() outside functions.

main.cpp:28: error: expected constructor, destructor, or type conversion before ‘(’ token

How do I initialize values in a static tm of a class?

Answer

Georg Fritzsche picture Georg Fritzsche · Jan 20, 2010

You can wrap the above in a function:

tm initTm() {
    time_t rawTime;
    ::time(&rawTime);
    return *::localtime(&rawTime);
}

tm Indice::dataTime = initTm();

To avoid possible linking problems, make the function static or put it in an unnamed namespace.