继承中的构造析构函数调用顺序

子类构造函数必须对继承的成员进行初始化:

  1. 通过初始化列表或则赋值的方式进行初始化(子类无法访问父类私有成员)

  2. 调用父类构造函数进行初始化

    2.1  隐式调用:子类在被创建时自动调用父类构造函数(只能调用父类的无参构造函数和使用默认参数的构造函数)

    2.2  显示调用:在含参构造函数的初始化列表调用父类构造函数(适用所有的父类构造函数)

#include <iostream>
#include <string>

using namespace std;

class PParent                //父父类
{
public:
    PParent(string s)
    {
        cout << "PParent" << s << endl;
    }
    ~PParent()
    {
        cout << "~PParent" << s << endl;
    }
};

class Parent : public PParent  // 父类
{
public:
    Parent() : PParent("Default")  
    {
        cout << "Parent" << endl;
    }
    Parent(string s) : PParent(s)
    {
        cout << "Parent" << s << endl;
    }
    ~Parent() 
    {
        cout << "~Parent" << endl;
    }
};

class sib_child              // 同级类
{
public:
    sib_child() 
    {
        cout << "sib_child" << endl;
    }
    sib_child(string s)
    {
        cout << "sib_child" << s << endl;
    }
    ~sib_child() 
    {
        cout << "~sib_child" << endl;
    }    
};

class Child : public Parent    // 自己
{
    Parent p;
    sib_child sc;
public:
    Child() : Parent(s),sib_child(s)
    {
        cout << "Child" << endl;
    }
    Child(string s) : Parent(s), sib_child(s) // 先调用父类构造函数,再调用同类构造函数
    {
        cout << "Child" << s << endl;
    }
    ~Child() 
    {
        cout << "~Child" << endl;
    }
};

int main()
{       
    Child cc("call : ");
    // 构造顺序
    // PParent   : call         父父类
    // Parent    : call          父类
    // sib_child : call         同类
    // Child     : call            自己

    return 0;
    // 析构顺序
    // ~Child     : call            自己
    // ~sib_child : call         同类
    // ~Parent    : call          父类
    // ~PParent   : call         父父类
}

构造函数调用顺序:

  1. 执行父类构造函数

  2. 执行同级构造函数

  3. 执行自己构造函数

析构函数调用顺序:

  1. 执行自己析构函数

  2. 执行同级析构函数

  3. 执行父类析构函数

原文地址:https://www.cnblogs.com/zsy12138/p/10846437.html