Why cant we initialize Const and reference varibales inside the constructor braces({ }) and is always done via initialization list
Thanks,
Sandeep
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The lifetime for a reference begins after it’s initialized (like all variables), and once it’s initialized it represents an alias to another variable. Consider:
You see, once we enter the constructor, all member variables are initialized. For a reference, this means it must be referring to a variable. Ergo, we must initialize it to refer to something in the initialization list.
Likewise, assigning to a
constvariable is illegal:const int x = 5; x = 2; // doesn't compile. It must be initialized to a value, and it will remain the value for its lifetime. Therefore, it too must be initialized in the initialization list.