我知道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;
}
Allocating space precedes initialization. Space allocation is completed first, and then member variables are initialized.
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.