- 3.3 派生类的构造与析构函数
- 3.3.1 构造
- 3.3.2 析构
3.3 派生类的构造与析构函数
3.3.1 构造
-
如果子类构造函数没有显式指明基类部分(基类子对象)的初始化方式,那么编译器将会自动调用基类的无参构造函数来初始化基类子对象。
-
如果希望以有参的方式来初始化基类部分,那么必须使用初始化列表来显式指明
-
子对象构造顺序
- 分配内存
- 构造基类子对象(按继承表顺序)
- 构造成员子对象(按声明顺序)
- 执行子类构造函数代码
#include <iostream> using namespace std;class Member{ private:int m_m; public:Member(){cout << "Member()" << endl;}Member(int m) {cout << "Member(int)" << endl;m_m = m;} };class Base { private:int m_i; public:Base(){cout << "Base()" << endl;}Base(int i){cout << "Base(int)" << endl;m_i = i;} };class Derived:public Base{ private:int m_d;Member m_me; public:Derived(){cout << "Derived()" << endl;//不指定作用域 默认调用无惨构造函数}Derived(int d):Base(d), m_me(d){ //指定作用域 就调用有参构造函cout << "Derived(int)" << endl;m_d = d;} }; int main (void) {Derived d1;Derived d2(100);return 0; }
3.3.2 析构
-
子类的析构函数,无论自己定义的,还是编译器缺省提供,都会自动调用基类的析构函数,完成基类子对象的销毁
-
子类对象销毁过程
- 执行子类析构函数代码
- 析构成员子对象(按声明逆序)
- 析构基类子对象(按继承表逆序)
- 释放内存
#include <iostream> using namespace std;class Member{ private:int m_m; public:Member(){cout << "Member()" << endl;}Member(int m) {cout << "Member(int)" << endl;m_m = m;}~Member(){cout << "~Member()" << endl;} };class Base { private:int m_i; public:Base(){cout << "Base()" << endl;}Base(int i){cout << "Base(int)" << endl;m_i = i;}~Base(){cout << "~Base()" << endl;} };class Derived:public Base{ private:int m_d;Member m_me; public:Derived(){cout << "Derived()" << endl;//不指定作用域 默认调用无惨构造函数}Derived(int d):Base(d), m_me(d){ //指定作用域 就调用有参构造函cout << "Derived(int)" << endl;m_d = d;}~Derived(){cout << "~Derived()" << endl;} }; int main (void) {Derived d1;return 0; }//输出结果: myubuntu@ubuntu:~/lv19/cplusplus/dy03$ ./a.out Base() Member() Derived() ~Derived() ~Member() ~Base()