Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Initializing static const structure variable

I'm trying to add a static constant variable to my class, which is an instance of a structure. Since it's static, I must initialize it in class declaration. Trying this code

class Game {
    public:
        static const struct timespec UPDATE_TIMEOUT = { 10 , 10 };

    ...
};

Getting this error:

error: a brace-enclosed initializer is not allowed here before '{' token

error: invalid in-class initialization of static data member of non-integral type 'const timespec'

How do I initialize it? Thanks!

like image 264
Kolyunya Avatar asked Aug 22 '12 18:08

Kolyunya


People also ask

Is it necessary to initialize const variables?

A constant variable is one whose value cannot be updated or altered anywhere in your program. A constant variable must be initialized at its declaration.

How do you initialize static constant characteristics of a class?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Can const be initialized?

A field marked as const can be initialized only at compile time. You need to initialize a field at runtime to a valid value, not at compile time. This field must then act as if it were a constant field for the rest of the application's life.

Can a static data member be const?

A static data member can be of any type except for void or void qualified with const or volatile . You cannot declare a static data member as mutable . You can only have one definition of a static member in a program.


1 Answers

Initialize it in a separate definition outside the class, inside a source file:

// Header file
class Game {
    public:
        // Declaration:
        static const struct timespec UPDATE_TIMEOUT;
    ...
};

// Source file
const struct timespec Game::UPDATE_TIMEOUT = { 10 , 10 };  // Definition

If you include the definition in a header file, you'll likely get linker errors about multiply defined symbols if that header is included in more than one source file.

like image 90
Adam Rosenfield Avatar answered Oct 25 '22 17:10

Adam Rosenfield