Static Gets Initialized!

Jul 22, 2015 at 5:10pm
I was testing out something with statics. My former experience says statics shouldnt be get initialized inside constructor. Thats why Static Constructor concept exist.

Yesterday to test something, i created a class that contains a static variable. It shouldn't get initialized but it did. I tested it with many ways, but everytime it got initialized.

So do i know wrong, or something has changed with C++ that i am not aware?

Here is the class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Header
class Foo
{
public:
    Foo();

    Foo(int random);

    ~Foo();

    int getVar1();

private:
    static int var1;
};

// Source
int Foo::var1;

Foo::Foo()
{
    int randomNum = rand();
    std::cout << randomNum << std::endl;
    var1 = randomNum;
}

Foo::Foo(int random)
{
    std::cout << random << std::endl;
    var1 = random;
}

Foo::~Foo()
{

}

int Foo::getVar1()
{
    return var1;
}

// Inside main
    Foo foo;

    std::cout << foo.getVar1() << std::endl;
Last edited on Jul 22, 2015 at 5:39pm
Jul 22, 2015 at 5:14pm
There is no such thing as a static constructor. The constructors in your program are just regular constructors that are called when you create an object.
Jul 22, 2015 at 5:35pm
By static constructor, i was talking about the static constructor concept not class constructor. My fault, not being able to explain it properly

Anyways question is, it shouldn't get initialized, but it gets initialized. Do i know it wrong?
Last edited on Jul 22, 2015 at 5:36pm
Jul 22, 2015 at 5:44pm
what's wrong is you are initializing it in your constructors (lines 24 and 30). Get rid of those two and your var1 will remain zeroed.

You can see that it is statically initialized by printing its value before you create any instances of Foo.

What it looks like you 'want' to do is have a static variable that indicates whether you have initialized the var1. If not, ctors should init it and set flag var to 'already initialized'.

Hope this helps.
Jul 22, 2015 at 5:50pm
Static variables are initialized to zero by default. You don't specify any value when you define var1 on line 18 so it gets initialized to 0.

Inside the constructors you assign a different value to var1. There is nothing special about static variables when it comes to assigning values. You can assign and it will get a new value just like any other variable.
Last edited on Jul 22, 2015 at 5:53pm
Jul 22, 2015 at 6:02pm
Yeah, it seems i knew it wrong. Sometimes i misunderstand simplest things.

Thank you guys.
Last edited on Jul 22, 2015 at 6:03pm
Jul 22, 2015 at 9:46pm
It was a good question. Everybody gets stupid stuff wrong.
Topic archived. No new replies allowed.