I l @ ve RuBoard |
14.3 Constant MembersClasses 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:
|
I l @ ve RuBoard |