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;
}
};
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).
The same... being a member function is orthogonal to being a static local.
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