Why should I prefer to use member initialization lists?

后端 未结 9 1484
醉酒成梦
醉酒成梦 2020-11-21 04:43

I\'m partial to using member initialization lists with my constructors... but I\'ve long since forgotten the reasons behind this...

Do you use member initialization

9条回答
  •  無奈伤痛
    2020-11-21 05:24

    1. Initialization of base class

    One important reason for using constructor initializer list which is not mentioned in answers here is initialization of base class.

    As per the order of construction, base class should be constructed before child class. Without constructor initializer list, this is possible if your base class has default constructor which will be called just before entering the constructor of child class.

    But, if your base class has only parameterized constructor, then you must use constructor initializer list to ensure that your base class is initialized before child class.

    1. Initialization of Subobjects which only have parameterized constructors

    2. Efficiency

    Using constructor initializer list, you initialize your data members to exact state which you need in your code rather than first initializing them to their default state & then changing their state to the one you need in your code.

    1. Initializing non-static const data members

    If non-static const data members in your class have default constructors & you don't use constructor initializer list, you won't be able to initialize them to intended state as they will be initialized to their default state.

    1. Initialization of reference data members

    Reference data members must be intialized when compiler enters constructor as references can't be just declared & initialized later. This is possible only with constructor initializer list.

提交回复
热议问题