Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many instances are there, of static variables declared in a method?

In this case, there should be only one or zero instances of the static variable. It depends whether f() has been called or not.

void f() 
{
    static int a;
}

But how many instances of the static variable are there if f() is a method?

class A
{
    void f()
    {
        static int a;
    }
};
like image 224
Martin Drozdik Avatar asked Jul 06 '12 05:07

Martin Drozdik


2 Answers

Same as for the function: 0 or 1. It is very easy to check too:

class A
{
public:
    void f()
    {
        static int a = 0;
        ++a;
        cout << a << endl;
    }
};


int main()
{
    A a;
    a.f();
    a.f();
    A b;
    b.f();
}

Output:

1
2
3

However, if you derieve from class A and make the function virtual like this:

class A
{
public:
    virtual void f()
    {
        static int a = 0;
        ++a;
        cout << a << endl;
    }
};

class B:public A
{
public:
    void f()
    {
        static int a = 0;
        ++a;
        cout << a << endl;
    }
};

then the a variable will be different for the base and for each derived class (because the functions are different too).

like image 180
SingerOfTheFall Avatar answered Sep 20 '22 12:09

SingerOfTheFall


The same... being a member function is orthogonal to being a static local.

like image 39
Tony Delroy Avatar answered Sep 21 '22 12:09

Tony Delroy