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!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With