Introduction to Programming and C++

Contents Previous Topic Next Topic

Static variables (variables which are shared by all instances of the class) may be declared to be constant (static class constants). Because the value cannot be changed, it is usually made public. Declaring the static variable to be constant allows the compiler to make certain optimizations: the compiler is aware that the value cannot be changed and may take advantage of this.

By convention, constants are written in all capital letters. A static class constant associated with the class ClassName is accessed outside by prefixing the constant with ClassName::.

Unlike non-constant static variables which cannot be assigned inside the class member declaration, constant variables can be assigned in the class member declaration. For example,

#include <iostream>
using namespace std;

class Constants {
	public:
		const static int ANSWER = 42;
		const static double NOT_PI = 3.241592653589793;
};

int main() {
	cout << "The answer to the ultimate question is " << Constants::ANSWER << "." << endl;
	cout << "A number not equal to pi is " << Constants::NOT_PI << "." << endl;

	return 0;
}

Contents Previous Topic Top Next Topic