Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static vars in a method body shared by all instances

Tags:

c++

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?

like image 896
Mr. Boy Avatar asked Mar 04 '10 15:03

Mr. Boy


People also ask

Are static variables shared between instances?

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class.

Are static methods shared?

They're still local variables - they're not shared between threads. The fact that they're within a static method makes no difference.

Do static data members belong to all instances of a class?

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.

Can static variables be used in instance methods?

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.


2 Answers

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.

like image 108
Raphaël Saint-Pierre Avatar answered Oct 06 '22 00:10

Raphaël Saint-Pierre


Every instance of MyClass will share one value i.

like image 35
kennytm Avatar answered Oct 05 '22 23:10

kennytm