If a non-static memeber function has a static local variable, I would have expected that there would be a separate albiet persistent copy of this variable for each object. Thus, defining
1 2 3 4 5 6 7
class A{
int someFunc(int n){
staticint local=0;
local+=n;
return local
}
};
Then in a driver program if I declare
A a1, a2, a3;
Then I would have expected inside a1.someFunc() the variable local would be different than the one inside a2.someFunc(). But this is not the case! There is a single copy of local across all objects! Question: What is the rational behind this, and more importantly how do I achieve the effect I want, namely different, but persistent copies of local for each separate object?
static variables in functions have nothing to do with classes, they are simply variables that exist from the first call of the function to the end of the program. They are never destroyed or reallocated, so the last value they had is the value they have the next time the function is called.
What you want is a non-static member variable:
8 9 10 11 12 13 14 15 16 17 18
class B
{
int local;
public:
B() : local(0) {}
int someFunc(int n)
{
local+=n;
return local;
}
};
It's the same function, operating on different instances of the class.
May be I should have given a better example. Suppose in the example above I want to keep track of of how many times someFunc() is invoked on each object. It cannot be a static class member since it is different for each object. I can accomplish this by having a non-static member, which is incremented inside someFunc().
But this somewhat pollutes the class. If I had several functions and I wanted to have a counter for each I would have a lot of class members lying around. So I am trying to have these counters encapsulated inside the functions themselves. How can this be done?