C++ - 派生类(derived class) 的 构造(construct) 和 析构(destruct)顺序 详解

时间:2022-09-07 21:17:21

派生类(derived class) 的 构造(construct) 和 析构(destruct)顺序 详解

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/16115261

 

派生类因为要调用基类, 所以构造和析构都是按照一定顺序进行;

构造的顺序是: 基(base) -> 派生(derived);即先构造基类, 再构造派生类;

因为 基类独立于派生类的, 即不会调用派生类中的对象, 所以应该先被生成;

如果派生类先于基类生成, 则因为无法调用基类资源, 可能生成失败;

析构的顺序是: 派生(derived) -> 基(base); 即先释放派生类, 再释放基类;

因为 派生类 需要先释放调用的基类资源, 所以应该优先释放;

如果基类先析构, 则有可能某些资源被派生类占用, 可能导致析构失败;

派生类的构造和析构顺序正好相反;

 

代码:

/*
* CppPrimer.cpp
*
* Created on: 2013.11.12
* Author: Caroline
*/

/*eclipse cdt*/

#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <cstddef>

using namespace std;

class Quote {
public:
//Quote() = default;
Quote() {
std::cout << "this is Quote constructor" << std::endl;
}
Quote (const std::string& book, double sales_price) :
bookNo (book), price (sales_price) {}
std::string isbn() const { return bookNo; }
virtual double net_price (std::size_t n) const { return n* price; } //虚函数
//virtual ~Quote() = default; //动态绑定析构器
virtual ~Quote() {
std::cout << "this is Quote destructor" << std::endl;
}
private:
std::string bookNo;
protected: //受保护类型
double price = 0.0;
};

class Disc_quote : public Quote { //抽象基类
public:
//Disc_quote() = default;
Disc_quote() {
std::cout << "this is Disc_quote constructor" << std::endl;
}
Disc_quote (const std::string& book, double price, std::size_t qty, double disc) :
Quote(book, price), quantity (qty), discount (disc) {}
double net_price (std::size_t) const = 0; //纯虚函数
virtual ~Disc_quote() override{
std::cout << "this is Disc_quote destructor" << std::endl;
}
protected:
std::size_t quantity = 0;
double discount = 0.0;
};

class Bulk_quote final : public Disc_quote { //final限定词, 无法被继承
public:
//Bulk_quote() = default;
Bulk_quote() {
std::cout << "this is Bulk_quote constructor" << std::endl;
}
Bulk_quote(const std::string& book, double p, std::size_t qty, double disc) :
Disc_quote(book, p, qty, disc) {} //使用基类的构造器
double net_price(std::size_t cnt) const override;
virtual ~Bulk_quote() override{
std::cout << "this is Bulk_quote destructor" << std::endl;
}
};

double Bulk_quote::net_price(std::size_t cnt) const
{
if (cnt >= quantity)
return cnt * (1-discount) * price;
else
return cnt * price;
}

double print_total(std::ostream &os, const Quote& item, std::size_t n)
{
double ret = item.net_price(n);
os << "ISBN: " << item.isbn() << " # sold: " << n << " total due: " << ret << std::endl;
return ret;
}

int main (void) {

Bulk_quote* bq = new Bulk_quote;
delete bq;

return 0;

}


输出:

this is Quote constructorthis is Disc_quote constructorthis is Bulk_quote constructorthis is Bulk_quote destructorthis is Disc_quote destructorthis is Quote destructor