天天看點

繼承(Inheritance)與複合(Composition)關系下的構造與析構

這裡探究繼承與複合關系下的構造與析構次序,是看侯捷先生的C++留下的問題。

第一種關系:

繼承(Inheritance)與複合(Composition)關系下的構造與析構
#include <iostream>
using namespace std;
class Base
{
public:
    Base()
    {
        cout << "ctor of base" << endl;
    }
    ~Base()
    {
        cout << "dtor of base" << endl;
    }
};
class Component
{
public:
    Component()
    {
        cout << "ctor of component" << endl;
    }
    ~Component()
    {
        cout << "dtor of component" << endl;
    }
};
class Derived : public Base
{
public:
    Derived()
    {
        cout << "ctor of derived" << endl;
    }
    ~Derived()
    {
        cout << "dtor of derived" << endl;
    }
protected:
    Component c;
private:
};
void objectplay(void)//通過調用這個函數觀察對象的析構與構造函數
{
    Derived d;
}
int main()
{
    objectplay();
    system("pause");
    return ;
}
           
繼承(Inheritance)與複合(Composition)關系下的構造與析構

結論:這種關系下,先執行父類構造函數,再執行複合類的構造函數,最後執行本類的構造函數。而析構次序反之。

第二種關系:

繼承(Inheritance)與複合(Composition)關系下的構造與析構

根據前面的結論推測:先執行Component的構造函數,再執行Base的構造函數,最後執行Derived的構造函數。

繼續閱讀