const and member list initialisation
Posted on 2003-12-04
Suppose I have a very simple class
const int a;
char z = "String";
m = new char[strlen(z) + 1];
//a = 10; <---------------(2)
Now, I have stated that 'a' is const. The compiler moans if I leave (2) as-is, stating that 'a' must be initialised in the initialisation list. So, first question is why does a const variable *have* to be initialised in the initialisation list, not just in the constructor body ?
Secondly, if I change (1) to be a const char*, and try the strcpy as in the body of the constructor, the compiler moans about not being able to convert parameter 1 from const char* to char*. Now, this problem vanishes when I initialise 'm' in the initialisation list (eg m("String") //unsafe I know ), again reinforcing the fact that const variables must be initialised in this manner. But what I would liike to learn now is what if I wanted to leave 'm' as const; I obviously cannot safely assign to m a string literal (as above); the memory has to be allocated first hence my call to 'new'. How would I go about this, or is the simple answer "I couldn't".
Cheers in advance.