C++ beginner here. I'm going through Eckels' "Thinking in C++" and am a little confused about his explanation of const in classes. He starts out by saying:
"Thus, when you create an ordinary (non-static) const inside a class, you cannot give it an initial value. This initialization must occur in the constructor, of course, but in a special place in the constructor. Because a const must be initialized at the point it is created, inside the main body of the constructor the const must already be initialized."
All well and good. So he goes on to introduce the constructor initializer list for this very purpose and says "This is the place to put all const initializations. " We're given this code snippet:
"size" is a const, so it's initialized in the constructor initializer list. But then he gives us another code snippet in which a non-cost data member is initialized in the constructor initializer list:Code:class Fred {
const int size;
public:
Fred(int sz);
void print();
};
Fred::Fred(int sz) : size(sz) {}
void Fred::print() { cout << size << endl; }
Am I right in thinking that he didn't have to do this and that "index" could have been set in the body of the constructor function?Code:class StringStack {
static const int size = 100;
const string* stack[size];
int index;
public:
StringStack();
void push(const string* s);
const string* pop();
};
StringStack::StringStack() : index(0) {
memset(stack, 0, size * sizeof(string*));
}