I am reading Thinking in C++, and meet a very strange problem regarding const array initialization. The content can be referred to page 356 and 357, for code C08: StringStack.cpp.
part of the code:
---------------- (Code 1)
The book says, const (non-static) members must be initialized in initialization list of constructor before entering the constructor body. But what about the const string* stack[size]? it is not initialized before entering the constructor body.Code:class StringStack { static const int size = 100; const string* stack[size]; // target to be discuss int index; public: StringStack(); void push(const string* s); const string* pop(); }; StringStack::StringStack() : index(0){ memset(stack, 0, size * sizeof(string*)); // initialization of point to const array } ....
The more strange thing is, when I try to add a const int array, and do the similar thing:
----------------(Code 2)
....Code:class StringStack { static const int size = 100; const string* stack[size]; // target to be discuss const int z[size]; // newly added int index; public: StringStack(); void push(const string* s); const string* pop(); }; StringStack::StringStack() : index(0){ for(int i = 0; i < size: i ++){z[i] = i;} //try to initialize const int array memset(stack, 0, size * sizeof(string*)); // initialization of point to const array }
the code will not compile (I am using VC++ 2008), and I am giving two error:
error C2439: 'StringStack::z' : member could not be initialized
error C2166: l-value specifies const object
When I change the array to const int* z[size], it go back to work, even I don't initialize them int the constructor:
----------------(Code 3)
Code:class StringStack { static const int size = 100; const string* stack[size]; // target to be discuss const int* z[size]; // change to pointer int index; public: StringStack(); void push(const string* s); const string* pop(); }; StringStack::StringStack() : index(0){ memset(stack, 0, size * sizeof(string*)); // initialization of point to const array } ....
My question is:
1. how to initialize a normal const array? I know adding static may solve the problem with external initialization, but my question is not that. More specific, how to made code 2 work?
2. why we don't need to do explicit initialization for code 3? Actually if I don't add memset(stack, 0, size * sizeof(string*)); in the constructor, it will compile also. That means, initialize the array of pointers to const is different, but where is the initialization happens? by compiler?



LinkBack URL
About LinkBacks




CornedBee