Sometimes it would be nice to have symbolic constants with class scope. For example, a class declaration might use the literal 30
to specify an array size. Because the constant is the same for all objects, it would be nice to create a single constant shared by all objects. You might think the following would be a solution:
class Bakery
{
private:
const int Months = 12; // declare a constant? FAILS
double costs[Months];
...
But this won’t work because declaring a class describes what an object looks like but doesn’t create an object. Hence, until you create an object, there’s no place to store a value. (Actually, C++11 provides for member initialization, but not in a way that would make the preceding array declaration work; Chapter 12 returns to this topic.) There are, however, a couple ways to achieve essentially the same desired effect.
First, you can declare an enumeration within a class. An enumeration given in a class declaration has class scope, so you can use enumerations to provide class scope symbolic names for integer constants. That is, you can start off the Bakery
declaration this way:
class Bakery
{
private:
enum {Months = 12};
double costs[Months];
...
Note that declaring an enumeration in this fashion does not create a class data member. That is, each individual object does not carry an enumeration in it. Rather, Len
is just a symbolic name that the compiler replaces with 30
when it encounters it in code in class scope.
Because the Bakery
class uses the enumeration merely to create a symbolic constant, with no intent of creating variables of the enumeration type, you needn’t provide an enumeration tag. Incidentally, for many implementations, the ios_base
class does something similar in its public section; that’s the source of identifiers such as ios_base::fixed
. Here fixed
is typically an enumerator defined in the ios_base
class.
C++ has a second way of defining a constant within a class—using the keyword static
:
class Bakery
{
private:
static const int Months = 12;
double costs[Months];
...
This creates a single constant called Months
that is stored with other static variables rather than in an object. Thus, there is only one Months
constant shared by all Bakery
objects. Chapter 12 looks further into static class members. In C++98 you can use this technique only for declaring static constants with integral and enumeration values. Thus, C++98 doesn’t allow you to store a double
constant this way. C++11 removes that restriction.
3.145.87.161