[C++] in-class initializer

C++11 introduced serveral contructor-related enhancements including:

  • Class member initializers
  • Delegating controctors

This article discusses about Class member initializers only.

 

Class member initializers are also called in-class initializers. C++11 follows other programming language that let you initializer a class member directly during its declaration:

Class M { // C++11
    int j = 5;    // in-class initializer
    bool flag(false);    // another in-class initializer
public:
    M();
};

M m1;    // m1.j = 5, m1.flag = false

The complier transforms every member initializers(such as int j = 5) into a controctor's member initializer. Therefore, the declaration of class M above is semantically equalment to the following C++03 class definition:

class M2{
    int j;
    bool flag;
public:
    M2(): j(5), flag(false) {}
}

If the constructor includes an explict member initializer for a member that also has an in-class initializer, the controctor's member intializer will override the in-class initializer.

class M2{
    int j = 7;    // in-class initializer
public:
    M2();    // j = 7
    M2(int i): j(i) {}    // overrides j's in-class intializer
};
M2 m2;     // j = 7
M2 m3(5);    // j = 5

 

Reference:

C++11 Tutorial: New Constructor Features that Make Object Initialization Faster and Smoother, smartbear.com

 

转载于:https://www.cnblogs.com/TonyYPZhang/p/6537330.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值