Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in instance methods

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?

like image 825
Davide Valdo Avatar asked Jan 29 '10 18:01

Davide Valdo


People also ask

Can static variables be used in instance method?

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.

Are instance variables and static variables the same?

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'.

How are static variables and static methods different from instance variables and instance methods?

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.

Can we declare instance variable as static in Java?

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.


2 Answers

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 :).

like image 78
Timo Geusch Avatar answered Sep 28 '22 04:09

Timo Geusch


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.

like image 33
dcp Avatar answered Sep 28 '22 04:09

dcp