Are parent class constructors called before initializing variables?

前端 未结 5 2146
谎友^
谎友^ 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:08

    think of derived class as extra addition or extension of its base class, addition so it adds to something (this something must already exists). then, another issue is initialization of members. here, you provided default constructor

    public:
      parent() : a(123) {};
    

    so the member will be default initialized with 123 even if you create parent this way:

    parent p;
    

    if there was no default constructor that initializes object with value

    class parent {
    public:
      int a;
    };
    

    than what will be by default in member depends, if the class is P.O.D then int will be default initialized to 0, but if it is not, i.e. you provide more members such as string or vector

    class parent {
    public:
      int a;
      std::string s;
      std::vector v;
    };
    

    int will have random value if there is no default constructor that initializes it.

提交回复
热议问题