c++中對象都是先構造成員變量,再調用自身的構造函數;故父類成員變量首先被構造,然後調用父類的構造函數,再構造子類的成員變量,最後調用子類的構造函數。
對象析構時與構造順序相反,子類先調用自身的析構函數,再調用子類成員變量的析構函數,再調用父類的析構函數,再析構父類的成員變量。
測試代碼如下:
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"this is Basetest construction"<<endl;
}
~Test()
{
cout<<"this is Basetest destruction"<<endl;
}
};
class Test2
{
public:
Test2()
{
cout<<"this is SonTest Construction"<<endl;
}
~Test2()
{
cout<<"this is SonTest Destruction"<<endl;
}
};
class Base
{
public:
Base()
{
cout<<"this is Base construction"<<endl;
}
~Base()
{
cout<<"this is Base Destructior"<<endl;
}
Test a;
};
class Son:public Base
{
public:
Son()
{
cout<<"this is Son construction"<<endl;
}
~Son()
{
cout<<"this is Son Destruction"<<endl;
}
Test2 a;
};
int main()
{
//Base a;
Son test;
}