tags:

views:

108

answers:

1

Why cant we initialize Const and reference varibales inside the constructor braces({ }) and is always done via initialization list

Thanks, Sandeep

+8  A: 

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:

int& x;

/// ...

SomeClassConstructor(void)
{ // initialization list is done, reference lifetime has begun, and
  // therefore is an alias. It already must alias a variable, then.

    x = 5; // setting whatever x is an alias for to 5
}

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 const variable 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.

GMan
@Sandeep -- this answers your question
hype
It is worth mentioning that once initialized, a reference-type variable always points to the same object; *it cannot be modified to point to another object.*
J.F. Sebastian
But why inilialize it in Initilazation list and not inside constructor( after open braces for C'tor).
Sandeep
You can't perform initialization in the constructor, only in the *initialization-list*.
Georg Fritzsche
The initializer list uses the constructors of the types in question. Once inside the constructor body ({}), all members are already constructed - and since you cannot assign new values to const variables or references, due to their very nature (operator=() not valid for const and accessing the referenced value instead of the reference itself for references), you have to initialize them in the only place you have access to their constructors - the initializer list.
DevSolar
@J.F Sebastian: Not points, refers. :) It always refers to the same object, and cannot be reseated. @Sandeep: Once you enter the constructor *all member variables are initialized and fully constructed.* The constructor is the place to run any additional start-up code, but initialization has passed. References must be *initialized* to refer to something. We can't initialize any member variables in the constructor body, they are all already initialized.
GMan
Thanks GMan. superb answer.
Sandeep