C++中成員變數 父類 子類構造析構順序
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;
}