Let's say I have this program:
class Foo {
public:
unsigned int bar () {
static unsigned int counter = 0;
return counter++;
}
};
int main ()
{
Foo a;
Foo b;
}
(Of course this example makes no sense since I'd obviously declare "counter" as a private attribute, but it's just to illustrate the problem).
I'd like to know how C++ behaves in this kind of situation: will the variable "counter" in the bar() method be the same for every instance?
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.
Instance variables are just variables defined inside a class, and every instance of a class can have a different value for an instance variable. In this module, we'll look at defining static variables in our Java classes. Static variables are also defined as variables inside a class, but with the keyword 'static'.
Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Static variables are created when the program starts and destroyed when the program stops. Instance variables can be accessed directly by calling the variable name inside the class.
The Static method similarly belongs to the class and not the instance and it can access only static variables but not non-static variables. We cannot access non-static variables or instance variables inside a static method.
Yes, counter
will be shared across all instances of objects of type Foo
in your executable. As long as you're in a singlethreaded environment, it'll work as expected as a shared counter.
In a multithreaded environment, you'll have interesting race conditions to debug :).
By "be the same for every instance" you mean there will be one instance of this variable shared across each class instance, then yes, that's correct. All instances of the class will use that same variable instance.
But keep in mind that with class variables you have to take things like multi-threading into account in many cases, which is a whole different topic.
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