Why must class members declared as const be initialized in the constructor initializer list rather than in the constructor body?
What is the difference
const and reference variables must be initialized on the line they are declared.
class Something
{
private:
const int m_nValue;
public:
Something()
{
m_nValue = 5;
}
};
would produce code equivalent to;
const int nValue; // error, const vars must be assigned values immediately
nValue = 5;
Assigning const or reference member variables values in the body of the constructor is not sufficient.
C++ provides another way of initializing member variables that allows to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.
You can assign values to variables in two ways: explicitly and implicitly: view plaincopy to clipboardprint?
int nValue = 5; // explicit assignment
double dValue(4.7); // implicit assignment
Using an initialization list is very similar to doing implicit assignments.
Remember that the member initialization list, used to initialize base and member data objects, is in the definition, not declaration of the constructor.
More on cpp-tutorial and Code Wrangler.