Share static variable among different class instances : member variable « Class « C++ Tutorial






#include <iostream>
using namespace std;
class MyClass {
    static int a;
    int b;
  public:
    void set(int i, int j) {
      a=i;
      b=j;
    }
    void show();
};

int MyClass::a;

void MyClass::show(){
  cout << "This is static a: " << a << endl;
  cout << "This is non-static b: " << b << endl;
}

int main(void){
  MyClass x, y;

  x.set(1,1);
  x.show();
  y.set(2,2);
  y.show();
  x.show();
}








9.5.member variable
9.5.1.Create a getter for member variable
9.5.2.Initialize member variable in constructor
9.5.3.Share static variable among different class instances
9.5.4.Output variable initialization message
9.5.5.Assign value to member variable directly from assignment
9.5.6.increment counter variable with ++ operator
9.5.7.Initialize member variable