首页 > 代码库 > [C++] in-class initializer

[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 initializerpublic:    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 initializerpublic:    M2();    // j = 7    M2(int i): j(i) {}    // overrides j‘s in-class intializer};M2 m2;     // j = 7M2 m3(5);    // j = 5

 

Reference:

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

 

[C++] in-class initializer