Are parent class constructors called before initializing variables?

前端 未结 5 2148
谎友^
谎友^ 2020-11-29 10:44

Are parent class constructors called before initializing variables, or will the compiler initialize the variables of the class first?

For example:

c         


        
5条回答
  •  盖世英雄少女心
    2020-11-29 11:13

    Just as some advice, you can usually just test things like this out yourself if you're not sure:

    #include 
    using namespace std;
    
    class parent {
    protected:
      int a;
    public:
      parent() : a(123) { cout << "in parent(): a == " << a << endl; };
    };
    
    class child : public parent {
      int b;
    public:
                // question: is parent constructor done before init b?
      child() : b(456), parent() { cout << "in child(): a == " << a << ", b == " << b << endl; };
    };
    
    int main() {
      child c;
      return 0;
    }
    

    prints

    in parent(): a == 123
    in child(): a == 123, b == 456
    

提交回复
热议问题