class MyClass
{
public:
void method2()
{
static int i;
...
}
};
Will every instance of MyClass
share one value i
, or will each instance have its own copy?
Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class.
They're still local variables - they're not shared between threads. The fact that they're within a static method makes no difference.
The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.
Instance method can access static variables and static methods directly. Static methods can access the static variables and static methods directly. Static methods can't access instance methods and instance variables directly. They must use reference to object.
static
, here, operates as in any regular function.
Which means that i
is static
within MyClass::method2
, so there is one and only one instance of it.
Having one instance of a variable per object is what instance variables are for.
Every instance of MyClass
will share one value i
.
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