views:

103

answers:

4
class MyClass
{
  static int staticInt;

  void instanceMethod( int param )
  {
    static int parameter = param;
  }
}

Clearly staticInt is shared between all instance of MyClass. But can different instances of MyClass have different values of parameter the static local variable within instaceMethod?

Update

What about between program executions? Certainly they could be different in multiple program instances? What defines "scope" there - the execution unit? The c++ runtime?

Update

Thanks - this helped me squash a critical bug. Wish I could accept them all, but I'm going with the first answer with no other criteria.

+5  A: 

There is exactly one instance of parameter.

If you want an instance of parameter for each instance of the class, use a nonstatic member variable.

James McNellis
+1  A: 

Yes, they both persist. They cannot have different values between instances.

James Roth
What about between program execution?
user144182
No, they do not persist between executions.
James Roth
+5  A: 

In order to have different values of parameter for different instances you have to make parameter a non-static member of the class.

In your current version all instances will share the same parameter object. All static objects behave exactly the same in that respect. The only thing that depends on the point of declaration is the scope of the name. i.e. the regions where the name is visible. As for the lifetime and the value-retaining properties of the variable - they are always the same. It that respect it is just like a "global" variable, regardless of where you declare it.

In your example, there's no difference between parameter and staticInt when it comes to their value-retaining properties. The only difference is that staticInt is accessible to all members of the class, while parameter is only accessible to instanceMethod method.

The language provides you with no means to create variables whose values persist between program executions. This kind of persistence has to be implemented manually.

AndreyT
@AudreyT - your first paragraph mentions making parameter a non-static member of the class. Is it common to refer to static local variables in instance methods as static member? Is this technically correct or rather since the effect is the same, we can consider it a static member?
user144182
@user144182: No, local static variables are not members of the class. In C++ "being a member" is a concept mostly related in scoping and naming, not to physical behavior.
AndreyT
A: 

the values are not persistent across program execution(between two different invocation of the same program )

pushkarpriyadarshi