As much as i know, constant class members must be initialized before the constructor runs, but since they cannot be initialized in the class body (as it is just a prototype), therefore we need to initialize it inside initializer list. My question is when does memory gets allocated to a constant variable, and what is the order of execution?
class constant
{
const int a;
public:
constant(int k):a(k)
{
cout<<"a is "<<a<<endl;
}
};
int main()
{
constant cl(5);
return 0;
}
EDIT: Is it true that constant variables need to be initialized at the point where they are allocated memory?
I think you have the wrong idea about
const. Think less of it as related to implementation details (like memory), or runtime, and more there as a means to help the programmer and for the compiler.It doesn’t matter when the memory gets allocated (although it’s before you construct the object, before entering the initializer list – not specified by the standard), what matters is you can only initialize the variable in the intializer list (pre C++11) or even the class definition for
constintegral types.