Static Members


Static Members

Static data members are members that exist only once, no matter how many instances of a class are created. These static members can be viewed almost like a global variable, except that they are accessed within an object. Remember that all objects (of the same or derived class) will share the same static member. You must declare the actual static variable outside the class definition ”and inside. For example:

 #include <iostream> 

enum Modes { off, on };

void TurnStreetLights( int Mode )
{
cout << "Traffic lights turned " << (Mode ? "on":"off")
<< endl;
}

class Cars
{
public:
Cars() {
if( CarsOnRoad == 0 )
TurnStreetLights( on );
CarsOnRoad++; };
~Cars() {
if( --CarsOnRoad == 0 )
TurnStreetLights( off );
};
private:
static int CarsOnRoad; // This defines CarsOnRoads as static
};

int Cars::CarsOnRoad; // Note 2nd declaration,
this is the actual variable
void main( void )
{
Cars Me;
}

Functions within classes may also be static, in which case they can only access other static functions or static data members.




OOP Demystified
OOP Demystified
ISBN: 0072253630
EAN: 2147483647
Year: 2006
Pages: 130

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net