构造函数和析构函数调用顺序

构造函数

基类构造函数,对象成员构造函数,派生类自身构造函数

  • (多个基类时,按继承顺序)
  • (多个对象成员时,按成员前后顺序)

析构函数

派生类自身的析构函数,对象成员析构函数,基类析构函数

  • (多个基类时,与构造时相反)
  • (多个对象成员时,与构造时相反)

对象成员的调用顺序只跟声明顺序有关,跟初始化列表没有关系

示例代码

#include<iostream>
using namespace std;
 
class A
{
public:
        A() {cout << "A constructor called" << endl;}
        ~A(){ cout << "A destuctor called" << endl; }
};
 
class B
{
public:
        B(){ cout << "B constructor called" << endl; }
        ~B(){ cout << "B destructor called" << endl; }
};
 
class C: public B
{
public:
        C(){ cout << "C constructor called" << endl; }
        ~C(){ cout << "C destructor called" << endl; }
 
private:
        A a1;
        B b1;
};
 
int main()
{
        C c;
    cout << "------------------------------\n";
    return 0;
}
B constructor called
A constructor called
B constructor called
C constructor called
------------------------------
C destructor called
B destructor called
A destuctor called
B destructor called

Related Post

发表评论

电子邮件地址不会被公开。 必填项已用*标注