Defining Class Constants
Sometimes, you need an internal constant that all instances of the same class share. In earlier stages of C++, an anonymous enum was used for this purpose:
class Allocator
{
enum { PAGE_SIZE=1024 };
//
};
Although this form is still in use, standard-compliant compilers offer a preferable method of defining class constants:
class Allocator
{
static const int PAGE_SIZE=1024;
public:
Allocator(int pages){ p=new char[pages*PAGE_SIZE];}
//
};
const int Allocator::PAGE_SIZE; //no initializer here
This kind of initialization is permitted only with const static members of
integral types. For any other type, use a member initialization list:
class Math
{
const static double PI;
//
};
const double Math::PI= 3.14159265358979;
Knowing When and How
The primary form of initializing members is a member initialization list. For const data, references and subobjects whose constructors take arguments, the use of a member initialization list is mandatory. As a special case, const static members of an integral type are initialized inside the class body. Other static data members are initialized when defined, outside the class body.