Complete listing of Variables02.cpp, Listing 2

/*File:  Variables02.cpp
This C++ program illustrates the use of a static
class variable.

The program defines a class named Variables02,
which declares a public static variable named 

The code in the main method accesses the class
variable three times in succession with no
requirement to instantiate an object of the
class.  The first access displays the initial
value of the variable.  The second access
modifies the value of the variable.  The third
access displays the modified value.

Note that in C++, static class variables cannot
be initialized inside the class.  A global
initializer is used to initialize the class
variable in this program.  You are required to 
initialize static class variables or they will 
not be in scope and will not be accessible.  The
required initialization syntax is:

type class_name::static_variable = value

Note that you must include the type of the static
variable when you initialize it.

The program displays the following output:

Press any key to continue

A good explanation of the use of static class
members in C++ is available at:


#include <iostream>
using namespace std;

class Variables02{
  //Declare a public static class variable.  See
  // initialization below.
  static int aStaticVariable;
};//End Variables02 class

int main(){
  //Access the static class variable without a
  // requirement to instantiate an object of
  // the Variables02 class.
  cout << Variables02::aStaticVariable << endl;
  Variables02::aStaticVariable = 6;
  cout << Variables02::aStaticVariable << endl;
  return 0;
}//end main

//Must initialize the static variable outside
// the class.  It is not in scope and cannot be
// accessed until it is initialized.  You must
// specify the type of the variable when you
// initialize it.
int Variables02::aStaticVariable = 0;

Listing 2