Home  >  Q&A  >  body text

c++基类和父类的空间分配是按照什么顺序进行的

我知道constructor是先基类,下面这段代码可以用父类的成员变量给基类赋值,是不是先为父类分配变量空间?

#include<iostream>
using namespace std;

class Base{
public:
    Base(int& a) :_base_a(a){ cout << "Base:"<<endl; }
    virtual ~Base(){};
private:
    int& _base_a;

};
class Parent : public Base{
public:
    Parent() :Base(_par_a){ cout << "Parent: "<<endl; }
    int _par_a;
};
void main(){
    Parent p;
    p._par_a = 1;
}
PHP中文网PHP中文网2714 days ago719

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:29:52

    Allocating space precedes initialization. Space allocation is completed first, and then member variables are initialized.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:29:52

    When you construct a p, C++ first opens up a space of sizeof(Parent), and then executes Base(_par_a) first. But _par_a has not been initialized at this time, so the value inside is uncertain. You can try printing the passed in value in the Base constructor.

    reply
    0
  • Cancelreply