Use a static instance variable : static instance variable « Class « C++ Tutorial






#include <iostream> 
using namespace std; 
 
class MyClass { 
  static int num; 
public: 
  void setI(int i) { num = i; }; 
  void display() { cout << num << " "; } 
}; 
 
int MyClass::num; // define num 
 
int main() 
{ 
  MyClass a, b; 
 
  a.display(); // prints 0 
  b.display(); // prints 0 
 
  a.setI(10); // set static num to 10 
 
  a.display(); // prints 10 
  b.display(); // also prints 10 
 
  return 0; 
}
0 0 10 10








9.25.static instance variable
9.25.1.Use a static instance variable
9.25.2.Refer to static variable through its class name
9.25.3.static data members