继承关系下构造析构顺序

#include<iostream>
using namespace std;

class Base
{
    public:
        Base(){
            cout << "Base ctor ..." << endl;
        }
        virtual ~Base(){
            cout << "Base dtor ..." << endl;
        }
};

class Derived:public Base
{
    public:
        Derived(){
            cout << "Derived ctor ..." << endl;
        }
        ~Derived(){
            cout << "Derived dtor ..." << endl;
        }
};

int main()
{
    Derived test;

    return 0;
}

程序运行结果:
Base ctor ...
Derived ctor ...
Derived dtor ...
Base dtor ...
inheritance

复合关系下的构造和析构

#include<iostream>
using namespace std;

class Component
{
    public:
        Component(){
            cout << "Component ctor ..." << endl;
        }
        ~Component(){
            cout << "Component dtor ..." << endl;
        }
};

class Container
{
    public:
        Container(){
            cout << "Container ctor ..." << endl;
        }
        ~Container(){
            cout << "Container dtor ..." << endl;
        }
        Component c;
};


int main()
{
    Container foo;
    return 0;
}

程序执行结果:
Component ctor ...
Container ctor ...
Container dtor ...
Component dtor ...
inheritance

继承和复合关系下的构造和析构

#include<iostream>
using namespace std;

class Component
{
    public:
        Component(){
            cout << "Component ctor ..." << endl;
        }
        ~Component(){
            cout << "Component dtor ..." << endl;
        }
};
class Base
{
    public:
        Base(){
            cout << "Base ctor ..." << endl;
        }
        virtual ~Base(){
            cout << "Base dtor ..." << endl;
        }
        int n;
};

class Derived:public Base
{
    public:
        Derived(){
            cout << "Derived ctor ..." << endl;
        }
        ~Derived(){
            cout << "Derived dtor ..." << endl;
        }
        Component c;
};

int main()
{
    Derived foo;

    return 0;
}

程序执行结果:
Base ctor ...
Component ctor ...
Derived ctor ...
Derived dtor ...
Component dtor ...
Base dtor ...

#include<iostream>
using namespace std;

class Component
{
    public:
        Component(){
            cout << "Component ctor ..." << endl;
        }
        ~Component(){
            cout << "Component dtor ..." << endl;
        }
};

class Base
{
    public:
        Base(){
            cout << "Base ctor ..." << endl;
        }
        virtual ~Base(){
            cout << "Base dtor ..." << endl;
        }
        
        Component c;
};

class Derived:public Base
{
    public:
        Derived(){
            cout << "Derived ctor ..." << endl;
        }
        ~Derived(){
            cout << "Derived dtor ..." << endl;
        }
        
};

int main()
{
    Derived foo;

    return 0;
}

程序执行结果:
Component ctor ...
Base ctor ...
Derived ctor ...
Derived dtor ...
Base dtor ...
Component dtor ...
inherit+comp