Why must const members be initialized in the constructor initializer rather than in its body?
Solution 1:
In C++, an object is considered fully initialised when execution enters the body of the constructor.
You said:
"i wanted to know why const must be intialized in constructor initializer list rather than in it's body ?."
What you are missing is that initialisation happens in the initialisation list, and assignment happens in the body of the constructor. The steps in logic:
1) A const object can only be initialised.
2) An object has all of its members initialised in the initialisation list. Even if you do not explicitly initialise them there, the compiler will happily do so for you :-)
3) Therefore, putting 1) and 2) together, a member which is const can only ever have a value assigned to it at initialisation, which happens during the initialisation list.
Solution 2:
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.