Introduction to Programming and C++

Contents Previous Topic Next Topic

Static variables are variables which are shared by all instances (if any) of the class: for example, such a variable could be used to store the number of instances of a given variable.

In many ways, a static variable is not different from a global variable, only it is associated with one particular class. If it is private, it can only be modified by class member functions. A static variable may not be initialized in the class declaration, but rather, it must be defined later. For example,

class AClass {
	private:
		static int count;
		// ...

	public:
		// ...
};

int AClass::count = 0;

A static variable may always be accessed from outside the class through the :: operator:

class AClass;

ostream & operator << ( ostream &, const AClass & );

class AClass {
	private:
		int value;           // member variable
		static int count;    // static variable

	public:
		// ...

	friend ostream & operator << ( ostream &, const AClass & );
};

int AClass::count = 0;

// print the value with the count in parentheses

friend ostream & operator << ( ostream & out, const AClass & ac );
	return out << x.value << "(" << AClass::count << ")";
}

Contents Previous Topic Top Next Topic