开发者

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

Why cant we initialize Const and r开发者_StackOverflow中文版eference varibales inside the constructor braces({ }) and is always done via initialization list

Thanks, Sandeep


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜