Order of calling base class constructor from derived class initialization list

后端 未结 3 1054
长发绾君心
长发绾君心 2020-11-30 10:49
struct B { 
  int b1, b2;  
  B(int, int);
};

struct D : B {
  int d1, d2;
// which is technically better ?
  D (int i, int j, int k, int l) : B(i,j), d1(k), d2(l)          


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 11:14

    The order is well defined. It does not depend on how you specify them while initializtion.
    Base class constructor B will be called first and then the member variables(d1 & d2) in the order in which they are declared.

    To explain the comment in @Andrey T's answer.

    class MyClass1: public MyClass2, public virtual MyClass3
    {
    
    
    };
    

    The order of calling the Base class constructors is well defined by the standard and will be:

    MyClass3  
    MyClass2
    MyClass1
    

    The virtual Base class MyClass3 is given preference over Base Class MyClass2.

提交回复
热议问题