A static member variable example. : Static « Language « C++






A static member variable example.

A static member variable example.


#include <iostream>
using namespace std;

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


int myclass::i;           // Definition of myclass::i. i is still private to myclass.

int main()
{
  myclass object1, object2;

  object1.setInt(10); 

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

  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.Use a static member variable independent of any object.Use a static member variable independent of any object.
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