/************************************************************************ *
The following example shows the declaration, initialization,
use, and scope of the static data member si and static member
functions Set_si(int) and Print_si().
* ************************************************************************/
// This example shows the declaration, initialization,
// use, and scope of a static data member.
#include <iostream.h>
class X
{
int i;
static int si;
public:
void Set_i(int i) { this->i = i; }
void Print_i() { cout << "i = " << i << endl; }
// Equivalent to:
// void Print_i(X* this)
// { cout << "X::i = " << this->i << endl; }
static void Set_si(int si) { X::si = si; }
static void Print_si()
{
cout << "X::si = " << X::si << endl;
}
// Print_si doesn't have a 'this' pointer
};
int X::si = 77; // Initialize static data member
void main()
{
X xobj;
// Non-static data members and functions belong to specific
// instances (here xobj) of class X
xobj.Set_i(11);
xobj.Print_i();
// static data members and functions belong to the class and
// can be accessed without using an instance of class X
X::Print_si();
X::Set_si(22);
X::Print_si();
}
/************************************************************************ *
This example produces the following output:
i = 11 X::si = 77 X::si = 22
* ************************************************************************/