【C++ Primer 第15章】定义派生类析构函数

 学习资料

• 基类和派生类析构函数执行顺序

定义派生类析构函数

【注意】定义一个对象时先调用基类的构造函数、然后调用派生类的构造函数;析构的时候恰好相反:先调用派生类的析构函数、然后调用基类的析构函数。

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base
 5 {
 6 public:
 7     Base()
 8     {
 9         cout << "Base contruction" << endl;
10     }
11     virtual ~Base()
12     {
13         cout << "Base deconstruction" << endl;
14     }
15 
16 };
17 
18 class Derived : public Base
19 {
20 public:
21     Derived(int i)
22     {
23         num = i;
24         cout << "Derived contruction " << num << endl;
25     }
26     virtual ~Derived()
27     {
28         cout << "Derived deconstruction" << num << endl;
29     }
30 private:
31     int num;
32 };
33 
34 int main()
35 {
36     Derived derived(1);
37 
38     Base* basePtr;
39     basePtr = new Derived(2);
40     delete basePtr;
41 }

输出结果:

猜你喜欢

转载自www.cnblogs.com/sunbines/p/9215445.html