在创建派生类对象时,构造函数的执行顺序是:
在调用构造函数时先调用基类的构造函数,在调用对象成员的构造函数,最后在调用派生类本省的构造函数。
例:
#include <iostream >
using namespace std;
class B1
{
public:
B1()
{
cout << "Construct B1"<<endl;
}
~B1()
{
cout<< "Destruct B1" << endl;
}
};
class B2
{
public:
B2()
{
cout << "Construct B2" << endl;
}
~B2()
{
cout << "Destruct B2 " << endl;
}
};
class D : public B2, public B1
{
public:
D() : B2( ), B1( )
{
cout << "Construct D" << endl;
}
~D()
{
cout << "Destruct D" <<endl;
}
private:
B2 b2;
B1 b1;
};
int main()
{
D d;
return 0;
}