14.3 Constant Members
Classes
may contain constant members. The problem is that constants behave a
little differently inside classes than outside. Outside, a constant
variable declaration must be initialized. For example:
const int data_size = 1024; // Number of data items in the input stream
Inside a class, constants are not initialized when they are declared.
For example:
class data_list {
public:
const int data_size; // Number of items in the list
// ... rest of the class
};
Constant member variables are initialized by the constructor.
However, it's not as simple as this:
class data_list {
public:
const int data_size; // Number of items in the list
data_list( ) {
data_size = 1024; // This code won't work
};
// ... rest of the class
};
Instead, because data_size is a constant, it must
be initialized with a special syntax:
data_list( ) : data_size(1024) {
};
But what happens if you want just a simple constant inside your
class? Unfortunately C++ doesn't allow you to do the
following:
class foo {
public:
const int foo_size = 100; // Illegal
You are left with two choices:
Put the constant outside the code: const int foo_size = 100; // Number of data items in the list
class foo { This makes foo_size available to all the world.
Use a syntax trick to fool C++ into defining a constant: class foo {
public:
enum {foo_size = 100}; // Number of data items in the list
This defines
foo_size as a constant whose value is
100. It does this by actually declaring
foo_size as a element of an
enum type and giving it the explicit value
100. Because C++ treats enums as integers, this
works for defining integer constants.
The drawbacks to this method are that it's tricky,
it works only for integers, and it exploits some holes in the C++
syntax that may go away as the language is better defined. Such code
can easily cause difficulties for other programmers trying to
maintain your code who aren't familiar with the
trick.
|