Is this allowed in c++?

M

Markus Ilmola

Is it really allowed to initialize a static class member by calling a
function?

class foo
{
public:
static int bar;
static float test;
};

int foo::bar = random_number();
float foo::test = read_value_from_config_file();

int main()
{
return 0;
}


It compiles fine with the GNU c++ compiler, but is it really allowed in
the c++ standart? And more importantly is it a safe thing to do?


All examples that a have found from the Internet only use predefined
values like this:

int foo::bar = 4;
float foo::test = 2.0;
 
A

Abdo Haji-Ali

Markus Ilmola said:
It compiles fine with the GNU c++ compiler, but is it really allowed in
the c++ standart? And more importantly is it a safe thing to do?


All examples that a have found from the Internet only use predefined
values like this:

int foo::bar = 4;
float foo::test = 2.0;

A static variable is a normal variable with a static duration (it is
allocated when the program begins and deallocated when the program
ends), so you can do whatever you want with it (Set it, reset it,
reference it...)

Abdo Haji-Ali
Programmer
In|Framez
 
R

Rolf Magnus

Markus said:
Is it really allowed to initialize a static class member by calling a
function?

Sure, why not? This is true for any variable with static storage duration.
class foo
{
public:
static int bar;
static float test;
};

int foo::bar = random_number();
float foo::test = read_value_from_config_file();

int main()
{
return 0;
}


It compiles fine with the GNU c++ compiler, but is it really allowed in
the c++ standart?
Yes.

And more importantly is it a safe thing to do?

It depends. If another static variable's constructor needs the value, you
can run into problems due to initialization order.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top