Use a static member variable independent of any object. : Static « Language « C++






Use a static member variable independent of any object.

Use a static member variable independent of any object.

#include <iostream>
using namespace std;

class myclass {
public:
  static int i;
  void setInt(int n) { 
     i = n; 
  }
  int getInt() { 
     return i; 
  }
};

int myclass::i;

int main()
{
  myclass object1, object2;

  
  myclass::i = 100;                      // set i directly,  no object is referenced.

  cout << "object1.i: " << object1.getInt() << '\n'; // displays 100
  cout << "object2.i: " << object2.getInt() << '\n'; // also displays 100

  return 0;
}


           
       








Related examples in the same category

1.Static function and static variableStatic function and static variable
2.Static function variableStatic function variable
3.Static Member Functions: its strictionsStatic Member Functions: its strictions
4.Static member functions: 'preinitialize' private static dataStatic member functions: 'preinitialize' private static data
5.A static member variable example.A static member variable example.
6.Init static data before object creationInit static data before object creation
7.A shared resource example.A shared resource example.
8.Usage and effect of a static data memberUsage and effect of a static data member