派生类析构会调用基类析构吗
时间: 2023-09-23 17:13:16 浏览: 101
定义一个document类,有数据成员name,表示文档名称。从document派生出book类,增加数据成员pagecount,表示书籍页数。在构造函数和析构函数中输出信息,观察基类与派生类的构造函数和析构函数的调用顺序。
代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
class document {
public:
document(const string& name) : name_(name) {
cout << "document constructor called: " << name_ << endl;
}
virtual ~document() {
cout << "document destructor called: " << name_ << endl;
}
protected:
string name_;
};
class book : public document {
public:
book(const string& name, int pagecount) : document(name), pagecount_(pagecount) {
cout << "book constructor called: " << name_ << ", " << pagecount_ << " pages" << endl;
}
~book() {
cout << "book destructor called: " << name_ << ", " << pagecount_ << " pages" << endl;
}
private:
int pagecount_;
};
int main() {
book b("The Lord of the Rings", 1178);
return ;
}
```
输出结果如下:
```
document constructor called: The Lord of the Rings
book constructor called: The Lord of the Rings, 1178 pages
book destructor called: The Lord of the Rings, 1178 pages
document destructor called: The Lord of the Rings
```
可以看到,先调用基类的构造函数,再调用派生类的构造函数;先调用派生类的析构函数,再调用基类的析构函数。
阅读全文